c++ - 常数变量乘以用户输入

标签 c++ variables constants user-input

我一直在尝试创建一个简单的程序,允许我在用户输入成功命中数 totalHits 后显示总分,方法是将该输入乘以常量 POINTS 导致另一个变量; 得分

我不认为创建这样的程序会有任何问题,但像往常一样,我错了.. 当我运行程序时 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;
}

最佳答案

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;

关于c++ - 常数变量乘以用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18713961/

相关文章:

c++ - 未初始化的变量会发生什么? C++

php - 是否可以使用像列表这样的函数/语言构造来连接到 str 变量?

python - 具有不明确标识符的空指针

c++ - 默认情况下 std::ofstream 是否截断或追加?

java - 声明一堆相似变量的最少行数

c - 如何在c中预定义一个数组?

Swift 闭包真的可以修改常量吗?

c++ - const char* 与字符串文字的使用

在参数中强制执行单一类型的 C++ 参数包

c++ - 为什么 valgrind 说基本的 SDL 程序正在泄漏内存?