Home > Net >  My rand() isn't really working in C specifically in Visual Studio 2019. I do have had "i
My rand() isn't really working in C specifically in Visual Studio 2019. I do have had "i

Time:04-01

My rand() gives out the same number (GPA) for every student.

srand(time(NULL));
    int gpa = 0   (rand() % (10 - 0   1));

    for (int i = 0; i < number; i  ) {
        cout << "Enter the student #" << i   1 << "'s name: ";
        getline(cin, pStudents[i]); cout << endl;
    }
    for (int i = 0; i < number; i  ) {
        cout << "Student " << pStudents[i] << " has GPA of: " << gpa << endl;
    }

CodePudding user response:

You only compute it once.

Here is how to fix it on your code:

srand(time(NULL));
for (int i = 0; i < number; i  ) {
    cout << "Enter the student #" << i   1 << "'s name: ";
    getline(cin, pStudents[i]); cout << endl;
}
for (int i = 0; i < number; i  ) {
    int gpa = 0   (rand() % (10 - 0   1));
    cout << "Student " << pStudents[i] << " has GPA of: " << gpa << endl;
}
  • Related