0

我的第一个 C++ 程序有问题。我写了这个计算器,但是由于某种原因,当我输入操作字符时它退出了。它没有显示任何错误或其他东西,它只是退出了。这是来自 Visual C++ 的代码

#include <iostream>

using namespace std;

int  main()
{
    float n1;
    float n2;
    float n3;
    int op;
    cout << "Welcome to my calculator" << endl;
    cout << "Type the first number: ";
    cin >> n1;
    cout << "Type the second number: ";
    cin >> n2;
    cout << "Type the number for the operation" << endl;
    cout << "1 = addition" << endl;
    cout << "2 = subvision" << endl;
    cout << "3 = multiply" << endl;
    cout << "4 = division" << endl;
    cin >> op;
    if(op == 1)
    {
        n3 = n1 + n2;
        cout << "The result is " << n3 << endl;
    }
    if(op == 2)
    {
        n3 = n1 - n2;
        cout << "The result is " << n3 << endl;
    }
    if(op == 3)
    {
        n3 = n1 * n2;
        cout << "The result is " << n3 << endl;
    }
    if(op == 4)
    {
        n3 = n1 / n2;
        cout << "The result is " << n3 << endl;
    }
    return 0;
}
4

2 回答 2

0

您可能想查看switch语句而不是您的多个ifs。然后,当您的预期案例都不匹配时,您的默认语句可以捕捉到正在发生的事情。

switch (op)
{
case 1:
{
   // add
   break;
}
// other cases
default
{
   // something unexpected, print an error
}
}
于 2013-08-08T12:11:20.387 回答
-1

你可以修复那个插入

system("pause");

在返回之前的最后(如果你在 Windows 下编码)

于 2013-08-08T12:11:18.530 回答