【问题标题】:Program will not exit a do-while loop程序不会退出 do-while 循环
【发布时间】:2014-01-26 03:42:57
【问题描述】:

我正在尝试用 C++ 制作一个简单的计算器。以下是部分代码:

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
    int math;
    int a1;
    int a2 = 0;
    int a3 = 1;
    int answer;
    int amount = 0;
    int achecker = 1;

    cout << "Welcome to my calculator! Type '1' to add, type '2' to subtract, "
            "type '3' to multiply, type '4' to divide, and type '5' to exit."
         << endl;
    cin >> math;

    while (math = 1)
    {
        cout << "Input how many numbers you wish to add:" << endl;
        cin >> amount;
        achecker = amount;
        do
        {
            cout << "Input the number you wish to add:" << endl;
            cin >> a1;
            answer = a1 + a2;
            a2 = a1;
            achecker = achecker - achecker + 1;
        } while (achecker < amount);
        cout << answer;
    }

我遇到的问题是当程序进入do-while循环时,它永远不会出来,它只是不断要求用户输入一个数字。我已经经历了几次,我不知道问题是什么。有人可以帮忙吗?

【问题讨论】:

  • 这个表达式achecker = achecker - achecker + 1;1 分配给achecker,不管它以前的值是什么(提示:achecker - achecker 是零;零加一是一)。
  • .. 并缩进代码
  • while(math=1) 看起来不太乐观。尝试while((cin &gt;&gt; math) &amp;&amp; (math != 5)) 并丢失其正上方的cin &gt;&gt; math
  • 你也错过了最终的}

标签: c++ calculator do-while


【解决方案1】:

您在 while 循环中进行了错误的条件检查。

match=1 是赋值操作而不是相等性检查,这是您正在尝试做的。赋值总是返回 1(true),所以你有一个无限循环。

match=1 替换为 match==1 以使您的代码正常工作

【讨论】:

  • 谢谢,但它仍然不断循环执行 do 循环。
  • 打印数量值以进行调试。它会有所帮助
【解决方案2】:

achecker = achecker - achecker + 1; 始终等于 1。所以我认为您在该行中有错误。

【讨论】:

    【解决方案3】:

    首先,您应该写 while(math==1) sicnce ma​​th=1 是赋值运算符而不是检查运算符。

    其次,使用 if 代替 while ,因为您只想计算一次加法,将其放入 while 循环中让它成为一个无限循环。

    第三,在do-while循环中,条件应该是while(achecker>=0),因为你的条件总是会给出一个真值。所以,实际上,不需要检查器,只需在每次循环运行时将数量减一并将条件保持为 while(amount>=0)

    一个,我想提出更多改进,虽然不是必需的 - 将 answer 声明为 int answer = 0;。对于每个循环运行,在 a1 中接受一个新值,然后为添加,编写 answer=answer+a1。这应该符合您的目的。

    所以,根据我的编辑代码应该是-

    #include <iostream>
    #include <string>
    #include <cmath>
    
    using namespace std;
    
    int main()
    {
      int math;
      int a1;
      int a3 = 1;
      int answer = 0;
      int amount = 0;
      int achecker = 1;
    
      cout << "Welcome to my calculator! Type '1' to add, type '2' to subtract, type '3' to      multiply, type '4' to divide, and type '5' to exit." << endl;
      cin >> math;
    
      if(math == 1){
      cout << "Input how many numbers you wish to add:" << endl;
      cin >> amount;
      do{
      cout << "Input the number you wish to add:" << endl;
      cin >> a1;
      answer = answer + a1;
      amount = amount - 1;
      }while(amount>=0);
      cout << answer;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      相关资源
      最近更新 更多