Having a little trouble figuring this one out, I have a bunch of int variables which are generating random numbers from 1-9. I need them to generate the correct numbers to equal to a certain number, for example 30.
int numone = rand()%10;
int numtwo = rand()%10;
int numthree = rand()%10;
int numfour = rand()%10;
int finalsum;
do{
finalsum = numone + numtwo + numthree + numfour;
}while(finalsum !=30);
I am not sure if I am going about this the right way but when I try to compile the above code, I don't even get a number and sometimes I get a "Time limit exceeded" error, perhaps it is taking too long. Is there another way I can do this?
The chance that you get '30' for a result is pretty small. You also don't get a random number from 1 to 9, you get them from 0 to 9.
Try this instead:
(Edit) After some lateral thinking:
numthree
needs to be between30-1-(numone+numtwo)
and30-9-(numone+numtwo)
-- perhaps there is room for a small further optimization there.(Further edit) After the deliberations below I actually tested it, and indeed, this works per requirement:
Well, i hope you realize that in your do while loop, you are not actually changing the values of the random numbers.What you are doing is basically checking the same condition of
finalsum = numone + numtwo + numthree + numfour;
infinitely if it does not equal 30.What you should do is:Move the
rand()
into the while loop, or you'll generate random numbers only once, and get stucked in while loop.