c++ 在while循环上调用函数

bis0qfac  于 2022-12-01  发布在  其他
关注(0)|答案(2)|浏览(164)

我正在编写一个计算器程序,但我已经遇到了一个问题。我的代码是在一个循环中,它将调用一个函数来显示选项,然后要求用户选择,a/s/m/d是选项。如果输入是在选项上,它将继续下一步。否则,它将循环,然后再次调用该函数。

#include <iostream>
using namespace std;

void home()
{
    cout << "\nChoose your operation:" << endl;
    cout << "\tType [A] for Addition" << endl;
    cout << "\tType [S] for Subtraction"<< endl;
    cout << "\tType [M] for Multiplication" << endl;
    cout << "\tType [D] for Division" << endl;
}

int main()
{
    char operation;
    bool no_operator = true;
    int design = 73;

    for (int i = 0; i < design; i++){
        if (i == 25){
            cout << " WELCOME TO CALCULATOR ";
            i += 22;
        }
        else i == 72 ? cout << "*\n" : cout << "*";
    }
    while (no_operator){
        home();
        cout << "\nOperation: ";
        cin >> operation;

        if (operation == 'A' || operation == 'a')
        {
            cout << "\nIt will going to add numbers";
            no_operator = false;
        }
        else if (operation == 'S' || operation == 's')
        {
            no_operator = false;
            cout << "\nIt will going to subtract numbers";
        }
        else if (operation == 'M' || operation == 'm')
        {
            no_operator = false;
            cout << "\nIt will going to multiply numbers";
        }
        else if (operation == 'D' || operation == 'd')
        {
            no_operator = false;
            cout << "\nIt will going to divide numbers";
        }
        else
        {
            cout << "\tInvalid Input: You must enter A/S/M/D only\n";
            //home();
        }
    }

    return 0;
}

我的问题是它会在else语句中运行'' home()'',即使第二个循环中的输入是正确的。
我想在输入正确时停止调用“home()”

xvw2m8pv

xvw2m8pv1#

你的程序工作得很好,因为输入是正确的,它不显示主页,而是打印消息,它将划分等。

bf1o4zei

bf1o4zei2#

你的代码运行得很好。确保你输入的字母是正确的。同样,对于这段代码,“do while()”循环会更好。

相关问题