-
November 16th, 2008, 08:39 AM
#1
loop loop loop
right so far ive got this to genrate 1 random that the user has to guess and if correct then the program will end what im trying to put in is if the user guess first time or over and over till they get it right to then tell the user how many guess they took to get it right just dunno i tried using a for loop but that didnt work as its giving me 0 any ideas
Code:
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string>
int main()
{
std::string pause;
int number;
int max_value = 10, x;
srand( (unsigned)time( NULL ));
rand();
x = rand()/ (RAND_MAX / max_value + 1);
std::cout << "guess the random number between 0 and 10: ";
std::cin >> number;
if (number > x)
std::cout << "number is lower than " << number;
if (number < x)
std::cout << "number is higer than " << number;
for (int i = 0; i < 10; ++i)
{
while (number != x)
{
std::cout << "\n";
std::cout << "try again: ";
std::cin >> number;
if (number > x)
std::cout << "number is lower than " << number;
if (number < x)
std::cout << "number is higer than " << number;
}
std::cout << "Guess is correct";
std::cout << " user took " << i << " tries";
std::cin >> pause;
return 0;
}
}
Last edited by curtcoollfgrg; November 16th, 2008 at 12:07 PM.
-
November 16th, 2008, 09:04 AM
#2
Re: loop loop loop
x = rand()/ (RAND_MAX / max_value + 1);
Are you sure that does what you want?
I don't have my IDE in front of me, but assuming RAND_MAX is 32767 and rand returns 5000,
32767 / 10 = 3276
3276 + 1 = 3277
5000 / 3277 = 1.
You want x = (rand () % 10) + 1;
You need to start using code tags.
You need a while loop.
while(number != x)
{
}
-
November 16th, 2008, 12:10 PM
#3
Re: loop loop loop
Just like GCDEF said, use a while loop. The following is pseudo code, you need to fill in the real code.
Code:
// Calculate your random number
x = ...;
// "number" will be what the user guesses
int number = -1;
// Number of times the user has guessed
int guesses = 0;
// Start asking the user for a guess
while (number != x)
{
// use cin to ask the user for a guess and store guess in "number" variable
...
// increment number of guesses
++guesses;
}
// Print how many times the user had to guess, this value is stored in "guesses";
NOTE: Please use code tags when posting code like: [code] your code [/code]
-
November 16th, 2008, 02:48 PM
#4
Re: loop loop loop
i get yah so using the guess++; anything then i enter in number so say then everytime i enter a varible it will then count how many times i entered a varible and then using cout to display the guess store and also using -1 will allow the number 0 to be entred as using 0 will end the program as it will think that ive all ready entred zero
-
November 18th, 2008, 10:22 AM
#5
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
|