首页 > 解决方案 > C ++中的意外循环行为

问题描述

// cai.cpp (Computer Assisted Instruction)
// This program uses random number generation to assist students learn multiplication

#include <iostream>
#include <iomanip>
#include <cstdlib> // contains prototypes for srand and rand
#include <ctime>
#include <cctype>
using namespace std;

int main() {
    int question();
    string status;
    int score{0};

    cout << "\nThis program will present you with 10 multiplication problems\n"
        << "enter the correct answer after the prompt\n"
        << "Enter Y for YES and N for NO\n"
        << "Do you want to try a game?";
    cin >> status;


    while(status == "Y" || status == "y") {
        for(int x{0}; x < 11; x++) {
            question();
            score = score + question();
        }
        // report total score
        cout << "\nTotal score is " << score << " out of 10";

        cout << "\nWould you like to play again?";
        cin >> status;
        if(status == "n" || status == "N") {
            break;
        }
    }
    cout << endl;
}

int question() {
    string responses();
    // use srand to generate the random nmber for the various problems
    srand(static_cast<unsigned int> (time(0)));
    int number1 = 1 + rand() % 12; // initialize random number
    int number2 = 1 + rand() % 12; // initialize random number
    int total = number1 * number2;
    int response;
    int score{0};

    cout << "\nWhat is " << number1 << + " times " << + number2 << + " ?";
    cin >> response;
    while (response != total) { // while answer is wrong, repeat question and wait for response
        cout << " \nThat is incorrect, try again: ";
        cin >> response;
    }
    if ( response == total) {
        cout << responses();
        score++; // increment score after each correct answer
    }

    return score;


}

string responses() {
    string res1 = "Well done, that is correct!\n";
    string res2 = "Congratulations, that is very accurate!\n";
    string res3 = "Wow!, I'm impressed\n";
    string res4 = "You're doing great! Keep up the good work.\n";
    srand(static_cast<unsigned int> (time(0)));
    int select{1 + rand() % 4};

    switch(select) {
        case 1: return res1;
        break;
        case 2: return res2;
        break;
        case 3: return res3;
        break;
        case 4: return res4;
        break;
        default: return " ";
    }
}  

当我编译并运行这个程序时,我希望它只循环 10 次,但它循环超过 10 次,我认为它与响应函数中的 switch 语句有关,但我不明白为什么它应该导致一个问题。任何解释将不胜感激。我已经修改了 main 函数中的 while 循环条件以循环不同的时间,但它总是循环显示 switch 语句中的所有可能响应。附上结果的屏幕截图,我将 while 语句修改为仅循环两次,但我的所有响应仍然显示,因此它最终循环了 4 次。程序执行而设置为循环两次

标签: c++c++11

解决方案


期望它只循环 10 次,但它循环超过 10 次

在你的循环中:

for(int x{0}; x < 11; x++)

x从 0 到 10,所以它循环了 11 次。


推荐阅读