ユーザーが成功したヒットの量を入力した後totalHits
、その入力に定数変数を掛けてPOINTS
別の変数にすることで、合計スコアを表示できる簡単なプログラムを作成しようとしました。score
.
このようなプログラムを作成しても問題ないと思いましたが、いつものように、私は間違っていました.. プログラムを実行すると、毎回score
「1」を入力しても、常にランダムです。totalHits
いくつかの例を挙げると、444949349 から -11189181 まで異なる場合があります。私は自分が何を間違えたのか分からないので、次に何をすべきかについて誰かが私に手がかりを与えることができれば素晴らしいと思います:)
コードは次のとおりです。
#include <iostream>
using namespace std;
int main()
{
const int POINTS = 50;
int totalHits;
int score = totalHits * POINTS;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;
}
正解を教えてくれた KerrekSB と Paddyd に感謝します。コメント付きの完成したコードは次のとおりです。
#include <iostream>
using namespace std;
int main()
{
const int POINTS = 50;
int totalHits;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
/*As you can see I moved the line below from the top of the code.
The problem was I had not properly learned how C++ executes the code.
The orignal code was written in a way that calculates `score` before
the user could decide it's value, resulting in a different total score than
it should have been. In the finished code, the user inputs what
value `totalHits` is, THEN score is calculated by using that value. */
int score = totalHits * POINTS;
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;
}