【解決方法】この C++ 加算計算機の何が問題になっていますか


こんにちは、C ++を独学しています。この追加計算機はコンパイルエラーを報告しませんが、間違った結果を生成します。何が間違っていますか。 ありがとう。

#include <iostream>
using namespace std;

int main() {
    int num1, num2, total;
    total = num1 + num2;
    
 
   cout << "enter first number";
   cin >> num1;
   cout <<"enter second number";
    cin >>num2;
    cout << "answer is" << total;
    return 0;
}

私が試したこと:

Android 用 Cxxdroid C++ コンパイラ

解決策 1

計算する必要があります total ユーザーから値を取得します。 の値 total 等号を含む行で計算されます。 たとえば、コードを次のように変更した場合

C++
int num1 = 10, num2 = 13, total;   // here we assign initial values to num1,num2
total = num1 + num2;  // this assigns the value 23 to total.
cout << "enter first number";
cin >> num1;
cout <<"enter second number";
cin >>num2;
// total is still 23 here, as assigned above
// we really should recalculate total here.
cout << "answer is " << total;  // prints "answer is 23"

おそらく、最後の出力ステートメントを endl プログラムの最後でカーソルが 1 行下に移動するようにします。

解決策 2

引用:

私は何を間違っていますか

追加する値を知る前に、追加を実行しています。

C++
#include <iostream>
using namespace std;

int main() {
    int num1, num2, total;
    total = num1 + num2; // move this after getting the second value to add
                         // and before displaying the result
    
 
   cout << "enter first number";
   cin >> num1;
   cout <<"enter second number";
    cin >>num2;
    cout << "answer is" << total;
    return 0;
}

コメント

タイトルとURLをコピーしました