简化课堂演示的代码

时间:2015-10-23 20:11:50

标签: c++

对于技术写作课程,我将领导并让其他同学(在使用Visual Studio 2013的学校计算机上)参与制作一个简单的猜测游戏程序。我试图尽可能地让它变得简单易懂,因为很多同学都不是程序员。

有什么我可以做得更简单或更容易理解吗?

using namespace std;
int main(){
    char response = 'y';

    while (response != 'n'){
        srand(time(NULL));
        int guess = -1;
        int answer = (rand() % 100) + 1;

        while (guess != 0){
            cout << "Guess a number between 1 and 100. Guess 0 to quit game." << endl;
            cin >> guess;
            if (guess == 0){
                break;
            }
            else if (guess == answer){
                cout << "Correct!" << endl;
                break;
            }
            else if (guess < answer){
                cout << "Too low, guess again!" << endl;
            }
            else {
                cout << "Too high, guess again!" << endl;
            }
        }
        cout << "Play again? (y/n): ";
        cin >> response;
    }
}

1 个答案:

答案 0 :(得分:1)

考虑放弃“再次播放”删除“猜0退出”。事实上,放弃“退出”,因为终端的Ctrl-C或关闭按钮已经存在。

answer重命名为不那么令人困惑的内容(picksecret)并将其设为const

提取“voodoo”的函数以生成随机数。使它更清晰!

while变为do {} while,以便在发生任何事情之前没有这种不直观的检查response != 'n'

while(guess!=0)相同。除此之外,你可以完全失去冗余条件。你已经有break ......

丢失else if,其中break已使分支冗余。

对缺少错误处理做出礼貌的评论......所以当他们的程序运行失败时,人们不会起诉你:)

另外,以递增方式写入,例如。

#include <iostream>

using namespace std;

void play_round();

int main() {
    srand(time(NULL));

    char response;
    do {
        play_round();

        cout << "Play again? (y/n): ";
        cin >> response;
    } while (response != 'n');
}

int pick_random(int from, int to) {
    return (rand() % (to-from+1)) + from;
}

void play_round() {
    const int secret = pick_random(1, 100);

    do {
        cout << "Guess a number between 1 and 100: ";

        int guess;
        cin >> guess;

        if (guess == secret) {
            cout << "Correct!" << endl;
            break;
        } 
    } while (true);
}

然后详细说明添加

        if (guess == 0) {
            break;
        }

最终

        if (guess < secret) {
            cout << "Too low, guess again!" << endl;
        }

        if (guess > secret) {
            cout << "Too high, guess again!" << endl;
        }

注意分支是如何独立的!

可选择详细说明:

int pick_random(int from, int to) {
    return (rand() % (to-from+1)) + from;
}

并使用pick_random(1, 100)等:)