-
February 22nd, 2011, 01:51 AM
#1
Rand() function
I'm trying to make a simple console game using Microsoft visual c++ 2010. It is a guessing game in which it creates a random number and you try to guess the number. There are two options, 1 to 10, or 1 to 100. The problem is it keeps generating a new random number every time i guess. I need the number to stay the same throughout the game. Does anyone know what the problem is?
Here is my code:
Code:
#include <iostream>
#include <time.h>
using namespace std;
void game1();
void game2();
void main() {
cout << "Guess the number" << endl;
cout << "----------------" << endl;
cout << "Please select an option" << endl;
cout << "1. 1 to 10" << endl;
cout << "2. 1 to 100" << endl;
int selection;
cin >> selection;
if (selection == 1) {
game1();
}
if (selection == 2) {
game2();
}
}
void game1() {
system("cls");
cout << "Guess the number (1 to 10):" << endl;
for (int times = 1;;times++) {
char answer;
int guess;
int number;
srand(time(0));
number = int(rand() % 10 + 1);
cin >> guess;
if (guess == number)
{
system("cls");
cout << "You win!" << endl;
cout << "It took you " << times << " times to guess." << endl;
cout << "Would you like to play again? (y/n)" << endl;
cin >> answer;
if (answer = 'y') {
game1();
}
if (answer = 'n') {
main();
}
system("pause");
}
else
if (guess > number) {
cout << "The number is less than " << guess << ". Guess the number (1 to 10):" << endl;
}
else
if (guess < number) {
cout << "The number is more than " << guess << ". Guess the number (1 to 10):" << endl;
}
}
}
void game2() {
system("cls");
cout << "Guess the number (1 to 100):" << endl;
for (int times = 1;;times++) {
char answer;
int guess;
int number;
srand(time(0));
number = int(rand() % 100 + 1);
cin >> guess;
if (guess == number)
{
system("cls");
cout << "You win!" << endl;
cout << "It took you " << times << " times to guess." << endl;
cout << "Would you like to play again? (y/n)" << endl;
cin >> answer;
if (answer = 'y') {
game2();
}
if (answer = 'n') {
main();
}
system("pause");
}
else
if (guess > number) {
cout << "The number is less than " << guess << ". Guess the number (1 to 100):" << endl;
}
else
if (guess < number) {
cout << "The number is more than " << guess << ". Guess the number (1 to 100):" << endl;
}
}
}
Last edited by Marc G; February 22nd, 2011 at 04:15 AM.
Reason: Added code tags
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|