Do while loop not working, please help

Apr 13, 2015 at 3:26pm
Sorry i am a complete noob i cannot seem to get the do-while loop to keep running until it meets the answer of valueGuessed == RandomNumber. Im trying to generate a random number which works, however the do-while loop is suppose to run again until the random number meets the number guessed, and it wont do that. Many thanks in advanced!

[# include <iostream>
# include <stdlib.h>
# include <time.h>
using namespace std;

void getGuess(int& valueGuessed)
{
cout << "I have a number between 1 and 1000" << endl;
cout << "Can you guess my number?" << endl;
cout << "Please type your first guess: " << endl;
valueGuessed = 0;
cin >> valueGuessed;
cout << "Your value is: " << valueGuessed << endl;
}

int isCorrect(int& valueGuessed, int& randomNumber)
{

srand(time(0));
randomNumber = 1 + rand()%1000;

do
{
if (valueGuessed < randomNumber)
{
cout << "Too low. Try again" << endl;
return(valueGuessed);

}
else if (valueGuessed > randomNumber)
{
cout << "Too high. Try again" << endl;
return(valueGuessed);
}
else if (valueGuessed == 0)
{
cout << "Wrong number" << endl;
return(valueGuessed);
}
} while(valueGuessed == randomNumber);


cout << "Excellent! You guessed the number!" << endl;
}


void display(int& answer)
{


}

int main()

{
int guess = 0, valueGuessed = 0, randomNumber = 0;
int answer;

getGuess(valueGuessed);
answer = isCorrect(valueGuessed, randomNumber);
display(answer);

return 0;
]
Put the code you need help with here.

[/
int isCorrect(int& valueGuessed, int& randomNumber)
{

srand(time(0));
randomNumber = 1 + rand()%1000;

do
{
if (valueGuessed < randomNumber)
{
cout << "Too low. Try again" << endl;
return(valueGuessed);

}
else if (valueGuessed > randomNumber)
{
cout << "Too high. Try again" << endl;
return(valueGuessed);
}
else if (valueGuessed == 0)
{
cout << "Wrong number" << endl;
return(valueGuessed);
}
} while(valueGuessed == randomNumber);


cout << "Excellent! You guessed the number!" << endl;
}


void display(int& answer)
{


}

int main()

{
int guess = 0, valueGuessed = 0, randomNumber = 0;
int answer;

getGuess(valueGuessed);
answer = isCorrect(valueGuessed, randomNumber);
display(answer);

return 0;]
Apr 13, 2015 at 3:29pm
while(valueGuessed == randomNumber) means that the loop will run while the 2 are equal, which I believe is the exact opposite if what you want.
Apr 13, 2015 at 4:43pm
Thanks! Any idea on how to make the programme reloop until programme reaches right number will be appreciated!
Apr 13, 2015 at 4:47pm
Firstly, please edit your post so all of your code is between [code]code tags[/code] - http://www.cplusplus.com/articles/jEywvCM9/

Since Your is the opposite of what you want as @Texan40 showed, you just have to do the opposite of the opposite to get it back on track right? So basically

while(valueGuessed != randomNumber) // this will run as long as the guessed value is not equal to the random number.
Topic archived. No new replies allowed.