我是新手,还是编程新手,所以在第一个类中,我做了下面的代码,除了最后一个“武器总数”,当我向numberPistols加+1时没有更新,其他一切都很好。我了解到numberPistols已更新,但是在最后一行使用numberWeapons时,它不显示新值。
我仍然不明白为什么,有人可以向我解释并告诉我我做错了什么吗?
#include <iostream>
using namespace std;
int main() {
int numberPistols = 5;
int numberKnives = 18;
int numberWeapons = numberPistols + numberKnives;
cout << "Number of Pistols: " << numberPistols << endl;
cout << "Number of Knives: " << numberKnives << endl;
cout << "Total of Weapons: " << numberPistols + numberKnives << endl;
cout << "There's a new Pistol available!" << endl;
numberPistols = numberPistols + 1;
cout << "New amount of Pistols " << numberPistols << endl;
cout << "Updated total of Weapons " << numberWeapons << endl;
return 0;
}
谢谢,最好的问候!
最佳答案
在此程序中,所有语句均按顺序执行,每个语句仅执行一次。 您必须重写或循环语句才能重复。
int numberPistols = 5;
int numberKnives = 18;
int numberWeapons = numberPistols + numberKnives;
让我们对程序进行一次试运行:
numberPistols
并将其初始化为值'5'。 numberKnives
并将其初始化为值'18'。 numberWeapons
,并使用从numberPistols
和numberKnives
的总和获得的值对其进行了初始化。 numberPistols
的值增加1。错误:
您已更新
numberPistols
,但尚未再次更新numberWeapons
。更改numberPistols
或numberKnives
的值不会影响numberWeapons
的值,因为它已经存储,并且您必须用新值更新存储的值才能进行更改。解决方案:
添加此行
numberWeapons = numberPistols + numberKnives;
numberPistols = numberPistols + 1;
之后现在,您的最终代码将是:
#include <iostream>
using namespace std;
int main() {
int numberPistols = 5;
int numberKnives = 18;
int numberWeapons = numberPistols + numberKnives;
cout << "Number of Pistols: " << numberPistols << endl;
cout << "Number of Knives: " << numberKnives << endl;
cout << "Total of Weapons: " << numberPistols + numberKnives << endl;
cout << "There's a new Pistol available!" << endl;
numberPistols = numberPistols + 1;
numberWeapons = numberPistols + numberKnives; //update the numberWeapons here
cout << "New amount of Pistols " << numberPistols << endl;
cout << "Updated total of Weapons " << numberWeapons << endl;
return 0;
}