0

I've been trying to create a simple program that allows me to display a total score after the user has entered the ammount of successful hits, totalHits, by multiplying that input with the constant variable POINTS resulting in another variable; score.

I didn't think creating such a program would be any problem, but as usual, I was wrong.. When I run the program score is always random, even if I enter '1' as totalHits every time. It can differ from 444949349 to -11189181 to name a couple of examples. I have no idea what I've done wrong, so it would be great if someone could give me a clue as to what to do next :)

Here's the code:

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

Big thanks to KerrekSB and Paddyd for providing me with the correct answer. Here's the finished code with comments:

#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 回答