-
help with rand
Hey, I'm back. YOu were right, Java is good for a while, but i ahd to come back to C++. anyway, I've tried to write a program that chooses a number, and the user has to guess it. I also want it to display the number of guess when the user is correct. I kind of forget what im doing, but this is what I have:
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char ans;
do {
int fav = std::rand() % 10;
int num;
int guess = 1;
do {
std::cout << "Pick a number from 1 to 10\n";
std::cin >> num;
if(num != fav){ ++guess;
}
std::cout << (num < fav ? "Low" :
num > fav ? "High" :
"You are Correct!\a\n It took you"
std::cout << guess<< "Guesses")
<< std::endl;
}while (num != fav);
std::cout << "Try again? y/n";
std::cin >> ans;
}while (ans == 'y');
return 0;
}
-
I think you want to use srand as well to seed the random number generator.
http://faq.cprogramming.com/cgi-bin/...&id=1043284385
-
> int fav = std::rand() % 10;
And if you want a number from 1 to 10, then make this:
int fav = std::rand() % 10 + 1;
-
If you have the line
using namespace std;
in your code, then you don't need to preface cin and cout with std::
Don't you the ternary operator for nested ifs. It makes your code incredibly unreadable.
-
I also recommend you pair up your braces
The code is a lot easier to read if the opening and closing braces of the same scope are lined up with each other.