我几乎已经完成了这个但是我一直遇到一个问题,我需要代码来显示用户输入数字的尝试次数,当我启动程序时它会显示尝试:0它应该但是如果我猜或低于随机数,它将不会显示尝试次数,直到第二次输入更高或更低,如果我输入随机数,它工作正常。
//bracketing search c++ beginner challenge
#include <iostream>
#include <string>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main() {
int guess; //Initializing the guess integer variable
int answer; //Initializing the answer integer variable
int t = 0;
srand(time(NULL)); // Prep for random number
answer = rand() % 100; // random number 0 - 99
cout << "hello please pick a number from zero to ninety nine " << endl; //Prompt the user to enter a number
cout << answer << endl; // just here to test what happens when number is correct
cout << "number of tries is : "<< t << endl;
cin >> guess; // getting the input of the guess variable
t++;
while (guess == answer) {
cout << "value of tries is : " << t << endl;
cout << "You picked the right number " << endl; //while loop, guess equal to answer then code executes, continue at the end so that it will ask until you guess the right number
break;
}
while (guess < answer) { //while loop guess smaller than answer
cout << "Pick a higher number " << endl; // Prompt the user to pick a higher number
cin >> guess; // input for the guess variable
t++;
cout << "value of tries is : " << t << endl;
continue; // brings back to the beggining of the loop
}
while (guess > answer) { //while guess variable is bigger than answer variable executes the code
cout << "Pick a lower number " << endl; //prompt the user to pick a lower number
cin >> guess; //Get input on user's next or first guess
t++;
cout << "value of tries is : " << t << endl;
continue; //brings the user back to the beggining of the while loop
}
system("pause"); // pauses system so the user can see what is in the command window
return 0; // return a value of 0 marking the end of the program
}
答案 0 :(得分:0)
你有太多while
个循环。大多数应该是if
s。你需要一个while
,直到猜测正确才结束。 (我使用do/while
循环):
....
do {
cout << "number of tries is : "<< t << endl;
cout << "hello please pick a number from zero to ninety nine " << endl;
// TODO: Add error checking in case user does not enter a number
cin >> guess; // getting the input of the guess variable
t++;
// change to if
if (guess < answer) {
cout << "Pick a higher number " << endl; // Prompt the user to pick a higher number
}
// Change to else if
else if (guess > answer) {
cout << "Pick a lower number " << endl; //prompt the user to pick a lower number
}
} while (guess != answer); // Loop until correct