首页 > 解决方案 > 如何将用户输入数字的尝试次数相加直到正确

问题描述

我几乎完成了这项工作,但我一直遇到一个问题,我需要代码显示用户输入数字的尝试次数,当我启动程序时,它显示尝试次数: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

}

标签: c++add

解决方案


你有太多的while循环。大多数应该是ifs。你需要一个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

推荐阅读