【问题标题】:C++ Calculator ExitsC++ 计算器退出
【发布时间】:2013-08-08 12:07:20
【问题描述】:

我的第一个 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;
}

【问题讨论】:

  • 它工作得很好。在控制台(cmd.exe)中运行它。
  • 或者它可能会打印结果,然后退出,但是这些发生得太近以至于您看不到结果?尝试在文件底部添加一个额外的cin &gt;&gt; something;
  • 为我工作 - 看起来您的输出正在通过管道传输到 VisualC 的输出日志。在控制台中运行它,看看它到底在做什么。
  • 如果您从 IDE 运行,请在 return 0; 行设置断点,然后尝试在调试模式下再次运行。
  • 只需在末尾添加一个 cin >> op 即可等待输入。它也适用于我。

标签: c++ calculator


【解决方案1】:

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

switch (op)
{
case 1:
{
   // add
   break;
}
// other cases
default
{
   // something unexpected, print an error
}
}

【讨论】:

  • 这并没有回答这个问题。这将是一个更好的评论。
【解决方案2】:

你可以修复那个白衣插入

system("pause");

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

【讨论】:

  • system("pause") 被认为是不好的做法,原因有很多。更好地使用cin.get()
猜你喜欢
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多