gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:10:04 26 4
gpt4 key购买 nike

我一直在尝试创建一个简单的程序,允许我在用户输入成功命中数 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com