Menu
CoddyTech

分支与范围

Coddy 面向 Python 开发者的 C++ 课程的第 8 课,共 48 课。

Python 使用缩进定义代码块,条件表达式会先写结果;C++ 使用花括号和条件运算符。C++ 使用花括号、if/else 链和条件运算符。if/else 链中只会执行一个分支。

Python

score = 8
if score >= 10:
    result = "high"
elif score >= 5:
    result = "mid"
else:
    result = "low"
print(result)

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

int main(){
int x=7;std::cout<<(x%2==0?"even":"odd")<<"\n";
}

分别跟踪每个程序。这些示例使用与任务不同的操作或数据来展示这个概念,不假设源代码和目标代码的输出相同。

challenge icon

挑战

简单

输入:整数温度。低于 10 时返回 cold,10 到 24(含)时返回 mild,25 及以上时返回 hot。

在 exercise.hpp 和 exercise.cpp 中实现已声明的 API。两个文件都可以编辑,请保留公开签名。锁定的 main.cpp 会读取标准输入并直接调用 API。如果有说明,它也会单独检查公开 API 的行为。在 API 内部返回值,不要打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。

亲手试试

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n;in>>n;std::cout<<weather(n)<<"\n";
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Python 开发者的 C++中的所有课

自己练习: C++ 在线编译器