我不懂打字

I do not understand type casting

本文关键字:不懂      更新时间:2023-10-16

我是一个编程新手,以前没有编程经验。我买了一本名为《绝对初学者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;
}

我对这个代码有一些问题:

  1. 在中,+=运算符是什么意思

    gold += silver / SILVERPERGOLD;

  2. 以下是什么意思?我不知道铸造是什么类型。

    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))将黄金的数量四舍五入为一个整数。小数部分已经转换为银,所以goldsilver这两个数字加在一起就构成了你所拥有的钱的总和。

整个行动试图将大量黄金纳入价格,并用白银弥补其余部分。千万不要这样做。