c++ - 如何将用户输入数字的尝试次数相加直到正确
问题描述
我几乎完成了这项工作,但我一直遇到一个问题,我需要代码显示用户输入数字的尝试次数,当我启动程序时,它显示尝试次数: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
}
解决方案
你有太多的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
推荐阅读
- python - ValueError: max_features=0, 使用 chunksize 提高速度时既不是正整数也不是 None
- java - 树 c# 中的 Java Access Bridge 文本框元素不可访问
- android - 为什么我使用的weatherstack api返回null?
- javascript - 重新连接后的 SignalR Hub 未从服务器获取消息
- python - 如何在烧瓶python中加入课程按钮?
- css - 使用 Flexbox 将列中的 div 元素对齐
- azure - 如何以 root 用户身份登录到 Azure Kubernetes pod
- javascript - 如何在特定元素中打印 html 代码标签?
- c# - Sentry 异常日志记录 .NET Core
- swift - 在 Swift 中将导航项标题移动到导航栏的右侧