2.6复习题
1.C++程序的模块叫什么?
函数。
2.下面的预处理器编译指令是做什么用的?
#include<iostream>
该预处理器编译指令将iostream文件的内容添加到程序中。在编译程序的时候自动执行
3.下面的语句是做什么用的?
using namespace std;
using编译指令使得std名称空间的所有名称都可以用
4.什么语句可以用来打印短语”Hello,world”,然后开始新的一行?
std::cout<<”Hello,world\n”;
5.什么语句可以用来创建名为cheeses的整数变量?
int cheeses;
6.什么语句可以用来将值32赋给变量cheeses?
cheeses = 32;
7.什么语句可以用来将从键盘输入的值读入变量cheeses中?
std::cin >> cheeses;
8.什么语句可以用来打印”We have X varieties of cheese,”,其中X为变量cheeses的当前值.
std::cout << “We have” << cheeses << ” varieties of cheese,”;
9.下面的函数原型指出了关于函数的那些信息?
int froop(double t);
void rattle(int n);
int prune(void);
第一个函数接受一个double值返回一个int值。第二个函数接受一个int值无返回值。第三个函数无接受值返回一个int值
10.定义函数时,在什么情况下不必使用关键字return?
当函数的返回值为Void类型的时候。
11.假设您编写的main()函数包含如下代码:cout<<”Please enter your PIN:”;而编译器指出cout是一个未知标识符.导致这种问题的原因很可能是什么?指出3种修复这种问题的方法.
原因:没有使用
#include<iostream>
。没有使用using namespace std;。
修复:使用#include<iostream>
。使用using namespace std;
。使用std::cout<<"Please enter your PIN:";
2.7编程练习
1.编写一个C++程序,它显示您的姓名和地址。
#include <iostream>
using namespace std;
int main(){
cout << "姓名:李文广,地址:南京。"<<endl;
system("pause");
}
2.编写一个c++程序,它要求用户输入一个以long为单位的距离,然后将其转换为码(1:220码)。
#include <iostream>
using namespace std;
int convert(int a){
return a * 220;
}
int main(){
int a;
cin >> a;
cout << convert(a) << endl;
system("pause");
}
3.编写一个c++程序,它使用3个用户自定义的函数生成下面的输出:
Three blind mice
Three blind mice
See how they run
See how they run
#include <iostream>
void fun1(void);
void fun2(void);
int main(){
fun1();
fun1();
fun2();
fun2();
std::cin.get();
return 0;
}
void fun1(){
std::cout << "Three blind mice\n";
}
void fun2(){
std::cout << "See how they run\n";
}
4.编写一个程序,让用户输入其年龄,然后显示有多少个月。
#include <iostream>
using namespace std;
int fun1(int);
int main(){
int month;
cin >> month;
cout << fun1(month) << endl;
system("pause");
}
int fun1(int age){
return age * 12;
}
5.编写一个程序,其中main()调用一个用户自定义的函数(以摄氏温度值作为参数,并返回相应的华氏温度值)。
#include <iostream>
using namespace std;
double fun1(double);
int main(){
double a;
cin >> a;
cout << fun1(a) << endl;
system("pause");
}
double fun1(double a){
return 1.8*a + 32.0;
}
6编写一个程序,其main()调用一个用户自定义的函数(以光年值作为参数,并返回对应的天文单位的值)。
#include <iostream>
using namespace std;
int fun1(int);
int main(){
double a;
cin >> a;
cout << fun1(a) << endl;
system("pause");
}
int fun1(int a){
return 63240 * a;
}
7编写一个程序,要求用户输入小数数和分钟数。在main()函数中,将这两个值传递给一个void函数,后合并显示时间。
#include <iostream>
using namespace std;
void fun1(int, int);
int main(){
int a,b;
cout << "Enter the number of hours: ";
cin >> a;
cout << "Enter the number of minutes: ";
cin >> b;
fun1(a, b);
system("pause");
}
void fun1(int a, int b){
cout << "Time:" << a << ":" << b;
}