Hello all. I am attempting to write a program that will generate a random number after entering 'y' or 'Y' when prompted. In each implementation, the program should first ask the user if they want to generate a random number, then if they answer ‘y’, generate and display a random number, otherwise exit.
Unfortunately, the program is sending back random numbers regardless of which key I hit, and not exiting at all. Any help with whatever I am missing here would be greatly appreciated. I will continue troubleshooting as well. Thank you.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
char generate;
double number =static_cast<double>(rand()) / RAND_MAX;
do
{
cout << "Do you want to generate a random number? (Enter 'y' for yes or 'n' for no.)" << endl;
cin >> generate;
}
while (generate=='y' || generate=='Y');
cout << "Random number: " << number << endl;
system("pause");
return 0;
}
Look at the do-while loop. What is inside it? Getting input from the user. That's it. So that loop will go around and around, doing nothing apart from getting an input from the user.
Where is the output of the random number? After the loop. So once the user says "n", you get out the random number and the program finishes.
I see. Would it have been better to use a different type of loop then? I'm also not very clear on outputting the random number. Thank you for your replies.
If you only want to ask them once I would have done it this way:
1 2 3 4
cout << "Do you want to generate a random number? (Enter 'y' for yes or 'n' for no.)" << endl;
cin >> generate;
if (generate=='y' || generate=='Y')
cout << "Random number: " << number << endl;
If you want to keep generating random numbers until they say no I would do:
1 2 3 4 5 6 7 8 9
cout << "Do you want to generate a random number? (Enter 'y' for yes or 'n' for no.)" << endl;
cin >> generate;
while (generate=='y' || generate=='Y')
{
number = static_cast<double>(rand()) / RAND_MAX;
cout << "Random number: " << number << endl;
cout << "Do you want to generate another random number? (Enter 'y' for yes or 'n' for no.)" << endl;
cin >> generate;
}