程序将不会退出DO-DO循环

Program will not exit a do-while loop

本文关键字:DO-DO 循环 退出 程序      更新时间:2023-10-16

我正在尝试在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-nile循环时,它永远不会出来,它只是不断要求用户输入一个数字。我已经过去了几次,我不知道问题是什么。有人可以帮忙吗?

您的状况错误在段循环中检查。

match=1是分配操作而不是平等检查,这是您要做的。作业将始终返回1(true),因此您有一个无限的循环。

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

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

首先,您应该编写 while(MATH == 1) sicnce MATH = 1 是分配操作员检查操作员。

其次,而不是 while ,使用 if >因为您只想进行一次添加一次计算,然后将其放入> loop will中使其成为无限的循环。

第三,在 do中 - 而loop ,该条件应为,而(achecker> = 0)实际上,不需要Achecker,只需在每个循环中保持一个降低量,然后将条件保持为,而(量> = 0)

我想提出的更多改进,尽管不是必需的 - 声明答案 AS int答案= 0; 。对于每个循环运行,请在A1中接受一个新值,然后添加,Write anders = anders 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;
  }