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

While loop and if/else statement not working correctly

本文关键字:语句 工作 不正常 else 循环 if While      更新时间:2023-10-16

我遇到的问题是,当我运行代码时,它会正确添加,但当运行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!nn";
cout<<"What is the first number you would like to add?nn";
cin>>firstNumber;
cout<<"What is the second number you would like to add?nn";
cin>>secondNumber;
cout<<"Wonderful! Getting together your result now....nn";
sum = firstNumber +   secondNumber;
cout<< sum<<endl;
cout<<"If you have another question, just enter 1, if not press 2!nn";
cin>>restart;
if (restart == 1)
{
cout<<"No problem!nn";
}
else
{
cout<<"Goodbye!";
}

}
return 0;
}
char restart = 1;
if (restart == 1)

需要

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

1和"1"之间存在差异。如果要比较char,请使用''标记。

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

这是因为C++不会自动将其设置为零。所以,你应该自己初始化它:

int sum = 0;

一个未初始化的变量有一个随机数,如654654、-5454等。(如果它在读取时没有调用未定义的行为(