C++ primer plus 课后练习题
以下代码均在Linux下ubuntu 18.04测试过
2.7.1
#include//using namespace std; int main() { //cout << "我的姓名是: 凯" << " 地址是: 江苏 南京" << endl; std::cout << "我的姓名是: 凯" << " 地址是: 江苏 南京" << std::endl; return 0; } //运行结果为:我的姓名是: 凯 地址是: 江苏 南京
2.7.2
#includeusing namespace std; int main() { long num = 0; cout << "Please input your number:"; cin >> num; cout << "转换为码为:" << num * 220 << "码" << endl; } // 运行结果如下 // Please input your number:2.5 // 转换为码为:440码
2.7.3
#includeusing namespace std; void func1(); void func2(); void func3(); int main() { func1(); func1(); func2(); func3(); return 0; } void func1() { cout << "Three blind mice" << endl; } void func2() { cout << "See how they run" << endl; } void func3() { cout << "See how they run" << endl; } //运行结果如下: // Three blind mice // Three blind mice // See how they run // See how they run
2.7.4
#includeusing namespace std; int main() { int age = 0; cout << "请输入您的年龄:"; cin >> age; cout << "该年龄包含" << age * 12 << "个月" << endl; return 0; } // 运行结果如下: // 请输入您的年龄:23 // 该年龄包含276个月
2.7.5
#includeusing namespace std; float func(int num) { return num * 1.8 + 32; } int main() { int num = 0; cout << "Please enter a Celsius value: "; cin >> num; float ret = func(num); cout << num << " degrees Celsius is " << ret << " degrees Fahrenheit" << endl; return 0; } // 运行结果如下: // Please enter a Celsius value: 21 // 21 degrees Celsius is 69.8 degrees Fahrenheit
2.7.6
#includeusing namespace std; float func(float years) { return years * 63240; } int main() { float years; cout << "Enter the number of light years:"; cin >> years; int ret = func(years); cout << years << " light years = " << ret << " astronomical units" << endl;; return 0; } // 运行结果如下: // Enter the number of light years:4.2 // 4.2 light years = 265608 astronomical units
2.7.7
#includeusing namespace std; void func(int hours, int minutes) { cout << "Time: " << hours << ":" << minutes << endl; } int main() { int hours, minutes; cout << "Enter the number of hours:"; cin >> hours; cout << "Enter the number of minutes:"; cin >> minutes; func(hours, minutes); return 0; } // 运行结果如下: // Enter the number of hours:9 // Enter the number of minutes:28 // Time: 9:28



