一、复习题
1.C++程序的模块叫什么?
答:函数。
2.下面的预处理器编译指令的功能是什么?
答:在编译器进行源代码的编译过程之前,将iostream头文件添加到当前源代码中替换当前编译指令。
3.下面语句的功能是什么?
答:using预编译指令的主要功能是表明当前源代码文件使用的名称空间std。
4.什么语句可以用来输出短语“Hello, world!”,然后开始新的一行?
答:cout << “Hello, world!” << endl; 或者 cout << “Hello, world!\n”; (第一种是C++风格,第二种是C语言风格,两种风格均可实现)
5.什么语句可以用来创建cheeses的整形变量?
答:声明定义语句,int cheeses;
6.什么语句可以用来将值32赋给变量cheeses?
答:赋值语句,cheeses = 32;
7.什么语句可以用来将从键盘输入的值读入变量cheeses中?
答:cin标准输入语句,cin >> cheeses;
8.什么语句可以用来输出"We have X varieties of cheese,",其中X为变量cheeses当前的值。
答:cout << “We have " << cheeses << " varieties of cheese,” << endl;
9.下面函数原型指出了关于函数的哪些信息?
答:
1)函数名为froop,返回类型为int,有一个参数double
2)函数名为rattle,无返回类型,有一个参数int
3)函数名为prunt,返回类型为int,没有参数
10.定义函数时,声明情况下不必使用关键字return?
答:通常当函数返回值为空(void)时,可以不需要return,函数的语句会依次执行到函数体的最后一条语句。
11.假设你编写的main函数包含如下代码:…
答:
1)使用预编译器指令声明:
using namespace std;
2)仅声明cout
using std::cout;
3)直接使用
std::cout<<" Please enter your PIN: " ;
二、编程练习
注意==:下面的代码只有主体部分,头文件的包含、名称空间的声明等需要读者自行补充。
1.编写一个C++程序,用于显示你的姓名和地址。
cout << "Your name" << endl;
cout << "Your address" << endl;
2.编写一个C++程序,它要求用户输入一个以long为单位的距离,然后将它转换为码(1 long = 220 码)
double distance; // 由于数据可能有小数,所以选择double
// 输入
cout << "请输入:";
cin >> distance;
// 输出转换后的结果
cout << "转换后:";
cout << distance * 220 << endl;
3.编写一个程序,它使用三个用户自定义的函数(包括main())
#include <iostream> // 标准输入输出头文件的包含
using namespace std; // 使用标准命名空间
// 函数声明
void print_mice();
void print_run();
int main()
{
// 调用函数
print_mice();
print_mice();
print_run();
print_run();
return 0;
}
// 函数定义
void print_mice()
{
cout << "Three bline mice" << endl;
}
void print_run()
{
cout << "See how they run" << endl;
}
4.编写一个程序,由用户输入其年龄,输出该年龄包含多少月。
// 4
int age;
cout << "请输入你的年龄:";
cin >> age;
cout << "一共" << age * 12 << "月" << endl;
5.编写一个程序,其中main()调用一个用户定义的函数(以摄氏温度值为参数,并返回相应的华氏温度值)。
// 函数声明
double convert(double c);
int main()
{
double c_degree, f_degree; // 定义两个double类型的变量,分别存储两种温度
// 输入
cout << "输入摄氏温度:";
cin >> c_degree;
// 转换
f_degree = convert(c_degree);
// 输出
cout << "对应的华氏温度为:";
cout << f_degree << endl;
return 0;
}
// 函数定义
double convert(double c)
{
double f = 1.8 * c + 32.0;
return f;
}
6.编写一个程序,其中,main()调用一个用户自定义的函数(以光年值为参数,并返回对应天文单位的值)
// 6
double light_year, astro_unit; // 定义两个double变量,存储光年值和转换后的天文单位
// 输入光年值
cout << "Enter the number of light years: ";
cin >> light_year;
// 转换并输出
astro_unit = light_year * 63240;
cout << light_year << " light year = "
<< astro_unit << " astronomical units."
<< endl;
7 .编写一个程序,要求用户输入小时数和分钟数。在main()函数中,将这两个值传递给一个void函数,后者以如下形式输出这两个值。
// 函数声明
void format_print(int hour, int minute); // 按题目格式打印小时和分钟
int main()
{
int hours, minutes; // 定义两个int类型的变量存储用户输入的小时数和分钟数
// 输入
cout << "Enter the number of hours: ";
cin >> hours;
cout << "Enter the number of minutes: ";
cin >> minutes;
// 调用函数格式化输出
format_print(hours, minutes);
return 0;
}
// 函数定义
void format_print(int hour, int minute)
{
cout << "Time: " << hour << ":" << minute << endl;
}
作者并未直接按照搬答案,其中也有我的个人思路。本人的水平有限,如果有错,请大家指出。我看到了一定会及时更正,感谢!!!