While循环和if / else语句无法正常工作

时间:2018-07-16 21:25:37

标签: c++ loops while-loop

我遇到的问题是,当我运行代码时,它可以正确添加,但是在运行ifelse语句时,什么也没发生。它总是会结束。

#include <iostream>
using namespace std;

int main()
{
   int firstNumber;
   int secondNumber;
   int sum;
   char restart = 1;

   while (restart == 1)
   {
      cout<<"Welcome to My Calculator!\n\n";
      cout<<"What is the first number you would like to add?\n\n";

      cin>>firstNumber;

      cout<<"What is the second number you would like to add?\n\n";

      cin>>secondNumber;

      cout<<"Wonderful! Getting together your result now....\n\n";
      sum = firstNumber +   secondNumber;
      cout<< sum<<endl;

      cout<<"If you have another question, just enter 1, if not press 2!\n\n";

      cin>>restart;
      if (restart == 1)
      {
         cout<<"No problem!\n\n";

      }
      else
      {

         cout<<"Goodbye!";
      }


   }
   return 0;
}

1 个答案:

答案 0 :(得分:4)

char restart = 1;
if (restart == 1)

需要成为

char restart = '1';
if(restart == '1') 

1和'1'之间有区别。当您要比较char时,请使用''标记。

此外,您还应该始终初始化int

这是因为C ++不会自动为您将其设置为零。因此,您应该自己对其进行初始化:

int sum = 0;

未初始化的变量具有一个随机数,例如654654,-5454等(如果读取时未调用未定义的行为)