我是编程方面的新手,之前没有编程经验。我为Mark Lee买了一本名为 C ++ Programming for the Absolute Beginner 的书(不是广告或任何东西),在第2课结束时(显示变量和忘记解释演员)他们给你这个游戏:
#include <iostream>
#include <string>
int main() {
using std::cout;
using std::cin;
using std::string;
string name;
cout << "Welcome to the weapon store, noble knight."
<< " Come to equip the army again?\n"
<< "What is your name? ";
cin >> name;
cout << "Well then, Sir " << name.c_str()
<< ", let's get shopping\n";
double gold = 50.0;
int silver = 8;
const double SILVERPERGOLD = 6.7;
const double BROADSWORDCOST = 3.6;
unsigned short broadswords;
cout << "You have " << gold << " gold pieces and "
<< silver << " silver." << "\nThat is equal to ";
gold += silver / SILVERPERGOLD;
cout << gold << " gold.\n";
cout << "How many broadswords would you like to buy?"
<< " (3.6) gold each ";
cin >> broadswords;
gold = gold - broadswords * BROADSWORDCOST;
cout << "\nThank you. You have " << gold << " left.\n";
silver = (int)((gold - (int)gold)) * SILVERPERGOLD;
gold = (double)((int)(gold));
cout << "That is equal to " << gold << " gold and "
<< silver << " silver. \n"
<< "Thank you for shopping at the Weapon Store. "
<< "Have a nice day, Sir " << name.c_str() << ".\n";
system("pause");
return 0;
}
我对此代码有一些疑问:
+ =运算符的含义是:
gold += silver / SILVERPERGOLD;
以下是什么意思?我对什么类型的铸件毫无头绪。
silver = (int)((gold - (int)gold)) * SILVERPERGOLD;
gold = (double)((int)(gold));
请不要因为我是一个菜鸟而讨厌我,请以新手理解的方式解释。谢谢!
答案 0 :(得分:1)
gold += silver / SILVERPERGOLD
+=
表示&#34;将+=
左侧的变量增加右侧的数量&#34;。
silver = (int)((gold - (int)gold)) * SILVERPERGOLD;
gold = (double)((int)(gold));
这是一种真正的,非常非常错误的浮点余数计算方法。
类型castiing是显式类型转换的另一个名称。
(double)x
表示&#34;取x
的值并返回相同的&#39;价值,但类型double
&#34;。如果x
为7,则结果为7.0。在C ++中进行类型转换是一种漫长的过时方式。 Google&#34; c样式演员&#34;了解更多信息。
相应地,
(int)x
表示&#34;取x并返回相同的&#39;值为int
&#34;。如果x是7.83,则结果为7(即,小数部分被丢弃)。
所以((gold - (int)gold))
意味着&#34;从gold
中减去整个部分,留下小数部分&#34;。然后,作者将结果乘以金到银的转换率,并将其向下舍入为整数。这大概给了我们银片的变化量。最后,通过gold = (double)((int)(gold))
,作者将金币数量减少到一个整数。小数部分已经转换为白银,因此两个数字gold
和silver
一起构成了您所拥有的金额。
整个操作试图将大量金币装入价格中,并用银来弥补其余部分。永远不要这样做。