如何简洁地编写"switch"语句以猜测用户正在考虑的数字

How to code 'switch' statements concisely to guess a number the user is thinking of

本文关键字:用户 数字 switch 简洁 何简洁 语句      更新时间:2023-10-16

我正在学习Bjarne Stroustrup的《Programming Principles and Practice Using c++》。在第4章中,你将创造一个游戏,让用户想出一个1到100之间的整数,然后计算机将提出问题来猜测答案。理想情况下,你应该在7个问题内得到答案。我的直觉是把每个可能范围的一半重复问多次,例如,一开始当范围的可能性是1到100时,问这个问题"你正在考虑的数字是大于还是等于50?"

下面是我的解决方案的一部分,展示了我是如何嵌套switch语句的:

char user_answer;
cout << "Is the number >= 50? Answer "yes" or "no" by inputting 'y' or 'n': an";
cin >> user_answer;
switch (user_answer)
{
case 'y':
    cout << "Is the number >= 75? Answer "yes" or "no" by inputting 'y' or 'n': an";
    cin >> user_answer;
    switch (user_answer)
    {
    case 'y':
        cout << "Is the number >= 87? Answer yes or no (you get the idea): an";
        cin >> user_answer;
        switch (user_answer)
        {
虽然假设创建每个最终的yes和no情况会产生准确的逻辑,但这段代码很难维护和创建。我应该尝试这个与while循环?功能呢?我尝试了一个'for'循环,但我无法实现上述逻辑的重复。

你应该想一个尽可能少重复代码行的方法。

是的,您应该使用while循环,并根据用户的答案进行适当的计算,以进一步缩小您在每次循环中询问的数字范围。

您应该考虑如何编写一段适用于提问每一步的代码,而不是web if语句。

作为一个例子,您可以存储一个可能值[1,100]的数组,并有一个反复出现的问题,询问它是否大于该数组的中心。

根据答案,您删除数组中不再可能的值,并从数组的新中心再次询问。从这里你只需要一个条件检查,看看你是否有一个大小为1的数组(意味着你知道答案)。

我刚刚开始在Stroustrup教材,以及。第4章介绍的概念:1. 迭代2. 功能3.向量看了这里发布的建议后,下面是我所拥有的。我做了大量的试验和错误,以确保我捕获了所有的数字。

cout << "Think of a number from 1 to 100, then press y and enter to continue.n";
char c;
cin >> c;
int min = 1;
int max = 100;
int half(int, int);
vector<int> number;
for (int i = min; i <= max; i++){
    number.push_back(i);
    }
cout << "Is your number from " << number[min - 1] << " to " << number[(max / 2) - 1] << "? y/n. n";
// the aim of this loop is to 
// 1. bring up the min number to the halfway point between min and max everytime user answer no.
// 2. bring  down the max number to the halfway point everytime user answer yes.
while((cin >> c)&&(min!=max)){
    if (c == 'n'){
        min = half( min, max);
        }
    else if (c == 'y'){
        max = (max + min) / 2;
    }
    else
    {
        cout << "I dont understand your input!n ";
    }

    cout << "min: " << min << "t max: " << max << 'n'; // track the limits of the number
    if (min == max){
        cout << "Your number is " << min << "!nPress ctrl-z!n";
    }
    else if ((min+max)%2)
    cout << " Is your number from " << number[min - 1] << " to " << number[half(min, max) - 2] << "? y/n.n";
    // because we added extra 1 in the half function for odd sums, we have to compensate here by deducting 2.
    else
    cout << " Is your number from " << number[min - 1] << " to " << number[half(min,max)-1] << "? y/n.n";
}
keep_window_open(); // part of std_lib header, prompts enter character to exit
}
int half (int x, int y){
    if ((x + y) % 2){
        return ((x + y) / 2) + 1; // because division always round down, so for odd number division we add 1 to be inclusive.
    }
    else
        return (x + y) / 2;

你应该去找一个函数,告诉它你想让它做什么。

这是一个留给改进空间的简单例子。但是您应该清楚地看到,有一个函数将参数作为输入。

这允许您多次使用该函数。我想我知道你想要编程的游戏,所以下一步是找到生成新值的数学方法,再次调用查询函数。

#include <iostream>
#include <string>
int QueryRange(int low, int high, int * result)
{
    int error = 0;
    using std::string;
    using std::cout;
    using std::endl;
    using std::cin;
    string str;
    cout << "Is your Number n in the following range? " << low << " <= n <=" << high << " (y/n)" << endl;
    cin >> str;
    if(0 == str.compare("n"))
    {
        *result = 0;
    }
    else if(0 == str.compare("y"))
    {
        *result = 1;
    }
    else
    {
        *result = -1;
        error = 1;
    }
    return error;
}

int main(int argc, char ** argv)
{
    using std::cout;
    using std::endl;
    int low = 1;
    int high = 100;
    int ret;
    while(0 != QueryRange(low, high, &ret))
    {
        cout << "Unable to read your input" << endl;
    }
    cout << "your answer was " << ((1 == ret) ? "y" : "n") << endl;
    return 0;
}

这是第4章练习4 p.128,是我在每个人输入后的解决方案。我不能直接使用人们的建议,因为我在教科书中的位置和问题的措辞是有限的。我能在7个或更少的问题中猜出用户号码。谢谢大家的意见。

// p128 Exercise 4 write a program to make a numbers guessing game. Use if, else,
// <, and =<, to find the answer of a number 1 to 100 in seven questions or less.
#include "C:UsersXDocumentsVisual Studio 2013Projectsstd_lib_facilities.h.txt"
int main()
{
char user_answer = ' ';
int min_val = 1;
int max_val = 100;
int quest_number = 0;
int x = 0;
cout << "Welcome to the guessing game!n-------------------------------------------------------------------------------nn";
cout << "Please think of a number from 1 to 100.n";
cout << "This program will guess what number you chose by asking you yes or no questions. Answer truthfully.nn";
cout << "Here is my first of seven questions or less. ";
quest_number = max_val / 2;
for (int i = 1; i < 8; ++i)
{
    if (min_val == max_val)
    {
        cout << "Test: min_val = " << min_val << ", max_val = " << max_val << ", i = " << i << "nn";
        cout << "The number you are thinking of is " << min_val << "!n";
        keep_window_open("~");
        return 0;
    }
    else if (max_val > 100 || min_val < 1 || min_val > 100 || quest_number > max_val || quest_number < min_val)
    {
        cout << "The program has had an error. Exiting.n";
        keep_window_open("~");
        return 0;
    }
    else if (max_val - min_val == 1)
    {
        cout << "Is your number greater than " << min_val << "? Answer yes or no by typing 'y' or 'n': a";
        cin >> user_answer;
        if (user_answer == 'y')
        {
            cout << "I figured it out! Your number is " << max_val << "!n";
            keep_window_open("~");
            return 0;
        }
        else if (user_answer == 'n')
        {
            cout << "I figured it out! Your number is " << min_val << "!n";
            keep_window_open("~");
            return 0;
        }
        else
        {
            cout << "That doesn't make sense.";
            keep_window_open("~");
            return 0;
        }
    }
    cout << "Question " << i << ": Is the number >= " << quest_number << "? Answer yes or no by typing 'y' or 'n': a";
    cin >> user_answer;
    if (user_answer == 'y')
    {
        min_val = quest_number;
        cout << "nTest: the question number = " << quest_number << "n";
        quest_number = min_val + (max_val - min_val) / 2;
        cout << "Test: the question number is now = " << quest_number << "n";
        cout << "Test: min_val = " << min_val << ", max_val = " << max_val << ", i = " << i << "nn";
    }
    else if (user_answer == 'n')
    {
        max_val = quest_number - 1;
        cout << "nTest: the question number = " << quest_number << "n";
        quest_number = min_val + (max_val - min_val) / 2;
        cout << "Test: the question number is now = " << quest_number << "n";
        cout << "Test: min_val = " << min_val << ", max_val = " << max_val << ", i = " << i << "nn";
    }
    else
    {
        cout << "There was an issue with your input.n";
        keep_window_open("~");
        return 0;
    }
}

}

相关文章: