簡體   English   中英

如何修復 c++ 中的此計算器錯誤?

[英]How do I fix this calculator error in c++?

我是編程新手,我遇到了這個問題,我不確定為什么 output 是否定的,有人可以解釋一下嗎? 編輯:感謝您的幫助!

#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

您的問題來自此檢查

  if (yes == 1) {

您要檢查的是 std::string 。 由於輸入的類型是字符串,因此您需要將其作為字符串而不是 integer。

像這樣的東西應該適合你:

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;
}

從您的程序中,我猜您想將多個數字相加。 問題是,您期待一個字符串並掃描一個 int。 這就是我所說的未定義行為,更不用說您是否要在掃描后明確地為其分配一個值。 你可能甚至不想掃描它。

這是您期望字符串並掃描字符串的方式:

std::string choice;

do {
    //whatever the hell you wanna do!
    std::cin >> choice;
} while (choice == "yes");

您以錯誤的數據類型將數據輸入到變量yes中。

所以我認為標准 I/O 線程已經崩潰,導致你不能給變量num3 並且num3未初始化。 memory 可能仍有一個不確定的值導致此結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM