hello c++ community,
Im a beginner in programming. I made a program that repeats my number input, Now I want to turn it the another way. I want the program to give me a random number and I will type it back.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main()
{
double x;
do {
cin >> x;
cout << x << endl;
} while (x);
}
Actually the example is almost exactly what you're asking, but I'm not sure of a better link to give you ;p
If you don't want to see that then just look at this
1 2 3
v1 = rand() % 100; // v1 in the range 0 to 99
v2 = rand() % 100 + 1; // v2 in the range 1 to 100
v3 = rand() % 30 + 1985; // v3 in the range 1985-2014
and apply it to your code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <cstdlib> // rand()
#include <ctime> //time()
#include <iostream>
int main()
{
srand(time(NULL)); //make a time seed
//this prevents your program from generating the same number each run
int rand_num = /*rand() number in some range, see above */
std::cout << "Guess what number the program just made!" << std::endl;
int guess;
cin >> guess;
//etc.
}
your right I had read the link that you give,
I see that I need to include another library, perhaps this 'cstdlib' is necessary to generate random number.
I try to play around and I will post my code afterwards.
Somehow I manage to make the program generate a random number
and I can retype that number but the problem is it also accepts other numbers that is not match to the random number it generated.
My aim is to retype only the random number and if I type a number that does not match it will say something like an error.
only set the seed srand(time(NULL)); once at the beginning of main. Delete line 23.
(Edit: Deleted a bunch of stuff, for some reason I thought rand() returned a double between 0 and 1, this is wrong, it's an int between 0 and RAND_MAX. I must've been thinking about some other language)
Your xRandom and xInput variable should be integers, there's no point to make them be double.
Usually you want a number to be within a certain defined range.
Doing xRandom = rand()%100 + 1 will make a random integer in range [1, 100]. This would make you actually able to guess it.
program exits if you copy the number
Maybe I'm misunderstanding you, isn't that what you want it to do? You're making it break if the number you entered equals the random number.
Adding cout statements to say if you guessed the number correctly or not would be good. You probably want line 25 to generate a number no greater than 1000 as well.
Aside from that, one little thing: Your while(xRandom) is basically the same thing as saying while(xRandom != 0). If you want the loop to still run even if rand() % 1000 happens to be 0, then I would just change it to a while(true) loop, or have a "bool correct" somewhere in there.