我不懂打字
I do not understand type casting
我是一个编程新手,以前没有编程经验。我买了一本名为《绝对初学者C++编程》的书,作者是Mark Lee(不是广告或其他什么),在第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 shoppingn";
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));
请不要因为我是个笨蛋而讨厌我,请用一个新手能理解的方式来解释。谢谢
gold += silver / SILVERPERGOLD
+=
的意思是"将+=
左侧的变量增加右侧的量"。
silver = (int)((gold - (int)gold)) * SILVERPERGOLD;
gold = (double)((int)(gold));
这是一种非常非常错误的浮点余数计算方法。
类型castiing是显式类型转换的另一个名称。
(double)x
表示"取x
的值,返回‘相同’但类型为double
的值"。如果x
为7,则结果为7.0。在C++中进行类型转换是一种早已过时的方法。谷歌"c风格的演员阵容"了解更多信息。
相应地,
(int)x
表示"取x并返回与int
‘相同’的值"。如果x为7.83,则结果为7(即小数部分被丢弃)。
所以((gold - (int)gold))
的意思是"从gold
中减去整个部分,留下小数部分"。然后,作者将结果乘以金银转换率,并将其四舍五入为整数。这大概给了我们银币的变化量。最后,作者用gold = (double)((int)(gold))
将黄金的数量四舍五入为一个整数。小数部分已经转换为银,所以gold
和silver
这两个数字加在一起就构成了你所拥有的钱的总和。
整个行动试图将大量黄金纳入价格,并用白银弥补其余部分。千万不要这样做。
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 我的神经网络不起作用 [XOR 问题]
- 请解释字谜的代码,我看不懂计数器数组,每个值已经是0
- Eulers 项目问题 no 345 听不懂几行代码
- C++:处理错误,看不懂我的错误
- 我不知道ROS代码的含义,也看不懂ros维基的例子
- 看不懂C++11模板函数参数推导
- 听不懂"std::cout"
- 看不懂二叉搜索功能
- 不懂一些C++语法
- 关于"make_shared"的错误,我看不懂
- 听不懂MPI_Bcast
- Qt串口,当我写的时候,我看不懂我写的东西
- 返回枚举,看不懂代码行
- C++11 auto/我有些不懂
- 我不懂打字
- c++代码:不懂
- 我听不懂科恩的话.osversion 14.5.0
- 看不懂这个向量声明
- 听不懂multi_index