【发布时间】:2013-09-10 08:23:57
【问题描述】:
我一直在尝试创建一个简单的程序,该程序允许我在用户输入成功命中数 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 为我提供了正确答案。这是使用 cmets 完成的代码:
#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;
}
【问题讨论】:
-
C++ 程序按顺序执行,一次一条语句。 C++ 是命令式的,而不是声明式的。你的意思是写 HTML 吗?
-
@KerrekSB 嗯,不:S 这应该是一个 C++ 程序。你是说我应该搬迁我的一些线路?
-
是的,虽然我必须说这是一个真的奇怪的问题。我的意思是,我可以看到你可能一直在想什么,但这根本不是 C++ 的工作原理:-S 一次一个语句,每个语句依次改变世界的状态......
-
@KerrekSB 好吧,你介意告诉我在哪里放什么吗?我像昨天一样开始写我认为是 C++ 的东西 ;) 所以我不知道该怎么做 :)
-
1.读取输入,2. 将输入乘以比例因子,3. 输出结果。
标签: c++ variables constants user-input