使用rand()函数的无限循环,因为一个mutatorc++

我有一个 Student 类,它有一个表示标志的私有成员。我也有一个标志设置器功能。

#include <iostream>
#include <cstring>


using namespace std;

class Student
{
private:
    string name;
    int flag;
public:
    Student(const string stname)
    :name(stname),flag(0)
    {
        cout << "Student with name " << name << " has been constructed!" << endl;
    };
    ~Student()
    {
        cout << "Student with name " << name << " to be destroyed!" << endl;
    };
    int get_flag();
    void set_flag(const int number);
};

以下是功能:

void Student::set_flag(const int number){  flag = number;}

int Student::get_flag(){  return flag;}

我主要尝试做的是选择一个随机数来表示循环数量和另一个随机数来选择要更改哪些学生对象标志。

编码:

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    string name;
    Student* students[44];
    for(int i=0; i<44; i++)
    {
       cin >> name;
       students[i] = new Student(name);
    }

   int how_many , which;
   srand (time(NULL));
                                //0-44 students can be changed
   how_many = rand() % 44 + 1; //how many students are going to be changed
   int j=1;
   while(j <= how_many) //which students are going to be changed
   {
       //i have 44 students so students array indexes range 0-43
       which = rand() % 43;
       if((students[which])->get_flag() == 1) continue;
       //if the student is not already picked to be changed
       if((students[which])->get_flag() != 1)
       {
          (students[which])->set_flag(1);
          j++;
        }
   }


    for(int i=0; i<44; i++) delete students[i];
}

为什么会导致死循环。真心好奇。看起来我真的没有做错什么。

回答

线

how_many = rand() % 44 + 1;

在最大情况下将设置how_many44

线

which = rand() % 43;

将设置which为 0 到 42(包括两者)之间的 43 个数字之一。

只有 43 个学生有他们的flag集合,所以j最多增加 43 次,最多只有 44。

how_many设置为 时44,这意味着条件j <= how_many永远不会为假并且循环将无休止地运行。

看来这条线which = rand() % 43;应该是which = rand() % 44;


以上是使用rand()函数的无限循环,因为一个mutatorc++的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>