[英]How do I fix this calculator error in c++?
I'm new to programming and I came across this problem im not sure why the output is negative can someone explain?我是编程新手,我遇到了这个问题,我不确定为什么 output 是否定的,有人可以解释一下吗? Edit: Thanks for the help!
编辑:感谢您的帮助!
#include <iostream>
using namespace std;
int main()
{
cout << "Enter your first number " << endl;
int num1;
cin >> num1;
cout << "Enter your second number" << endl;
int num2;
cin >> num2;
cout << "Would you like to add a third number, if your answer is yes enter yes, if your
answer is no enter no" << endl;
int yes;
cin >> yes;
yes = 1;
int sum;
if (yes == 1) {
cout << "Enter another number" << endl;
int num3;
cin >> num3;
sum = num1 + num2 + num3;
cout << "Sum = " << sum << endl;
} return 0;
output: Enter another number
Sum =-858993440
Your issue is coming from this check您的问题来自此检查
if (yes == 1) {
What you want to be checking for is a std::string instead.您要检查的是 std::string 。 Since the inputted type is a string you need to take it as a string instead of a integer.
由于输入的类型是字符串,因此您需要将其作为字符串而不是 integer。
Something like this should work for you:像这样的东西应该适合你:
int main() {
int num1 = 0, num2 = 0, sum = 0;
std::string yes;
std::cout << "Enter your first number " << std::endl;
std::cin >> num1;
std::cout << "Enter your second number" << std::endl;
std::cin >> num2;
std::cout << "Would you like to add a third number, if your answer is yes enter yes, if you answer is no enter no"
<< std::endl;
std::cin >> yes;
if (yes == "yes") {
std::cout << "Enter another number" << std::endl;
int num3 = 0;
std::cin >> num3;
sum += num3;
}
sum += num1 + num2;
std::cout << "Sum = " << sum << std::endl;
return 0;
}
From your program, I am guessing that you want to add multiple numbers together.从您的程序中,我猜您想将多个数字相加。 The problem is, you are expecting a string and scanning an int.
问题是,您期待一个字符串并扫描一个 int。 That is what I would term undefined behaviour, Not to mention if you are going to assign it a value explicitly just after scanning it.
这就是我所说的未定义行为,更不用说您是否要在扫描后明确地为其分配一个值。 you probably do not even want to scan it.
你可能甚至不想扫描它。
This is how you expect a string and scan one:这是您期望字符串并扫描字符串的方式:
std::string choice;
do {
//whatever the hell you wanna do!
std::cin >> choice;
} while (choice == "yes");
You input a data onto the variable yes
in the wrong datatype.您以错误的数据类型将数据输入到变量
yes
中。
So I think the standard I/O thread has crashed and cause you can not give a value to the variable num3
.所以我认为标准 I/O 线程已经崩溃,导致你不能给变量
num3
。 And the num3
is not initialized.并且
num3
未初始化。 The memory maybe still has a uncertain value that makes this result. memory 可能仍有一个不确定的值导致此结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.