《C++ Primer Plus》——编程练习答案(1)

来源:互联网 发布:linux local 编辑:程序博客网 时间:2024/05/21 08:00

第二章
学习这本书顺便写的,有错请大家指正。

2.7.1编写一个c++程序,显示您的姓名和地址。

//显示姓名和地址#include <iostream>int main(){    using namespace std;    cout << "姓名: 皮球" << endl;    cout << "地址: 广东省广州市" << endl;    cin.get();    return 0;}

运行结果
这里写图片描述

2.7.2编写一个c++程序,它要求用户输入一个以long为单位的距离,然后将其转换为码(一long等于220码)。

#include <iostream>int main(){    using namespace std;    cout << "Please input a num: ";    int distance_long;    cin >> distance_long;    cout << "The result is: " << distance_long * 220 << endl;    cin.sync();                    //清空输入流    cin.get();    return 0;}

运行结果
这里写图片描述
这里提一下 很多刚刚入门的朋友在cin输入数据后使用一个cin.get()是无法使程序暂停的,原因是输入数据时的换行符还在输入流之中,cin.get()会读取换行符而不发生暂停。
有以下三种解决方法:
①使用cin.sync()清空输入流,再使用cin.get()暂停;
②使用cin.get()读取换行符,再使用一个cin.get()暂停;
③头文件包含cstdlib库,调用system(“pause”);

2.7.3编写一个c++程序,它使用3个用户自定义的函数生成下面的输出:
Three blind mice
Three blind mice
See how they run
See how they run

#include <iostream>using namespace std;void func_1();void func_2();void func_3();int main(){    func_3();    cin.get();    return 0;}void func_1(){    cout << "Three blind mice" << endl;}void func_2(){    cout << "See how they run" << endl;}void func_3(){    func_1();    func_1();    func_2();    func_2();}

运行结果
这里写图片描述

2.7.4编写一个程序,让用户输入其年龄,然后显示有多少个月。

#include <iostream>int  main(){    using namespace std;    cout << "Enter your age :  ";    int num_age;    cin >> num_age;    cout << "The month of this age is:   " << 12 * num_age << endl;    cin.sync();    cin.get();    return 0;}

运行结果
这里写图片描述

2.7.5编写一个程序,其中main()调用一个用户自定义的函数(以摄氏温度值作为参数,并返回相应的华氏温度值)。

#include <iostream>double trans_ctoh(double x);int main(){    using namespace std;    cout << "Please enter a Celsius value: ";    double d_c,d_h;    cin >> d_c;    d_h = trans_ctoh(d_c);    cout << d_c << " degrees Celsius is " << d_h << " degrees Fahrenheit." << endl;    cin.sync();    cin.get();    return 0;}double trans_ctoh(double x){    return 1.8*x + 32.0;}

运行结果
这里写图片描述

2.7.6编写一个程序,其main()调用一个用户自定义的函数(以光年值作为参数,并返回对应的天文单位的值)。

#include <iostream>double change(double x);int main(){    using namespace std;    cout << "Enter the number of light year : ";    double x;    cin >> x;    double y;    y = change(x);    cout << x << " light years = " << y << " astronomical units.";    cin.sync();    cin.get();    return 0;}double change(double x){    return 63240 * x;}

运行结果
这里写图片描述

2.7.7编写一个程序,要求用户输入小数数和分钟数。在main()函数中,将这两个值传递给一个void函数,后合并显示时间。

#include <iostream>using namespace std;void show_time(int x, int y);int main(){    int hours, minutes;    cout << "Enter the number of hours: ";    cin >> hours;    cout << "Enter the number of minutes: ";    cin >> minutes;    show_time(hours,minutes);    cin.sync();    cin.get();    return 0;}void show_time(int x, int y){    cout << "Time: " << x << ":" << y << endl;}

运行结果
这里写图片描述

第二章只要注意函数的声明和数据流中残留的换行符即可。

0 0
原创粉丝点击