CodeCombat C++
第 1-8 关
📘

C++ 魔法运算手册

String & Number Operations

"字符串" + 拼接
数字 + - * / %
🔗

字符串拼接 (String Concatenation)

在 C++ 中,我们可以使用 + 号将文字连接起来,就像拼积木一样。

第1关:友和敌中,你需要呼叫朋友的名字:

while(true) { auto friend = hero.findNearestFriend(); if(friend) { // 结果: "去战斗, Alice!" hero.say("去战斗, " + friend.id + "!"); } }
注意:变量 friend.id 代表朋友的名字(字符串)。

拼接演示

"Hello "
+
name
Result: "Hello Hero"
🧪

字符串 + 数字 (String + Number)

在 CodeCombat 的 C++ 环境中,你可以直接把数字和字符串加在一起!系统会自动把数字变成文字。

第2关:似曾相识的味道中,我们要唱药水之歌:

auto potions = 10; // 拼接数字和字符串 hero.say(potions + " potions of health!"); // 输出: "10 potions of health!" hero.say("Take " + 1 + " down."); // 输出: "Take 1 down."
📜 + 🔢
自动转换

(提示:在标准的 C++ 中通常需要 std::to_string(),但在游戏中直接用 + 即可)

基础数学运算 (Math)

第5关:巫师之门中,你需要通过计算获得通关密码。

+加法 (Add)
-减法 (Sub)
*乘法 (Mult)
/除法 (Div)
auto las = hero.findNearestFriend().getSecret(); auto erz = las + 7; // 加法 auto sim = erz / 4; // 除法 auto aga = sim * las; // 乘法 hero.say(aga);
🧮
🧊

数据类型:整数与小数

[Image of C++ data types]

第6关:巫师出没中,除法可能会产生小数。

  • int: 整数 (如 1, 5, 100)
  • float: 浮点数/小数 (如 2.5, 3.14)
  • auto: 让电脑自己猜类型 (魔法关键字!)
// 使用 auto 自动推断类型 auto zso = hero.findNearestFriend().getSecret(); // 或者显式使用 float 存储小数结果 float mih = zso / 4; hero.say(mih);
10
int
2.5
float
auto = ?
🥇

优先级与括号 (Order of Operations)

[Image of order of operations pyramid]

魔法规则:先乘除,后加减

第7关:巫师天际层中,如果需要改变计算顺序,必须使用括号 ()

auto esz = 10; // 错误:先算 3-2=1,再乘 esz // auto tam = esz * 3 - 2; // 正确:如果你想先减法 auto zso = (esz - 1) * 4; // 复杂混合运算 auto csi = (tam + zso) * (zso - ist);
( )

* / %

+ -
📦

综合实战:变量与步骤

第8关:真炼金术中,我们需要按步骤处理金币。

int main() { auto wizard = hero.findNearestFriend(); // 1. 加法 auto sum = wizard.goldCoins + wizard.silverCoins; hero.say(sum); // 2. 减法 (利用上一步的 sum) auto sub = sum - wizard.bronzeCoins; hero.say(sub); // 3. 乘除 auto div = sub / 3; hero.say(div * 2); return 0; }
⚗️
Step by Step
🦉

C++ 魔法小贴士

; 分号
每一行代码结束必须加分号 ;,否则魔法会失效!
auto 关键字
当你懒得写 intfloat 时,用 auto 让电脑帮你决定。
区分大小写
heroHero 是不一样的!
🧙‍♂️