0

ユーザーが成功したヒットの量を入力した後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;
}
4

1 に答える 1

2
int totalHits;
int score = totalHits * POINTS;

初期化されていない変数 ( totalHits) を掛けています! この計算を行う前に、totalHits に値を適用する必要があります。

次のようなコードを使用してみてください。

const int POINTS = 50;
int totalHits;
int score;

cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
score = totalHits * POINTS;                   //totalHits has a value here
cout << "score is " << score << " ." << endl;

cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;
于 2013-09-10T08:27:15.000 に答える