How do I fix this code?

I'm trying to work on a program that does even division only. But I can't get multresult to be less than highestNum how do i do that?


for (int count = 1; count <= numquestions; count++)
{

number1 = 1+rand() % highestNum;
number2 = 1+rand() % highestNum;


multresult = number1*number2;

cout << multresult << " / " << number1 << " = " << endl;


correctanswer = multresult/number1;

cin >> studentanswer;

// Determines the winner
determinewinner();

if (studentanswer == correctanswer)
totaldivcorrect = totaldivcorrect +1;
else
totaldivwrong = totaldivwrong +1;



}
Try writing out an example of the bounds.

Say highestNum == 10
and rand() == 49

so number1 will equal to 1 + 49%10 == 10
then the same with number2 will equal to 10

multresult == 10*10 == 100

There'll only be a limited number of cases where multresult <= highestNum based on your code...


ps: Another thing to note is that calling rand() twice in a row like that will return the same value. I'm not sure if that's a desired result. If it's not then u'll have to seed it between calls.

Last edited on
@soranz
Er, no, calling rand() twice in a row like that is perfectly fine (and you'll get different values each time).

You'll get the same value if you were to do something like
1
2
3
4
srand(time(0));
number1 = 1+rand() % highestNum;
srand(time(0)); // Reseed...with the same value (most of the time, at least) as before
number2 = 1+rand() % highestNum;

So you should only seed rand once (typically at the start of the program).
Topic archived. No new replies allowed.