总结
函数由函数头和函数体组成。函数头指出函数的返回值(如果有的话)的类型和参数类型。
函数先声明(或先定义),后使用。
提示:以下是本篇文章正文内容,下面案例可供参考
一、第一题
题目:编写一个C++程序,它显示您的姓名和地址
#include <iostream>
int main() {
std::cout << "中盾" << std::endl;
std::cout << "中国" << std::endl;
return 0;
}
二、第二题
题目:编写一个C++程序,它要求用户输入一个以long为单位的距离,然后将它转换为码(一long等于220码)。
#include <iostream>
int main() {
float longDistance;
std::cout << "请输入一个以long为单位的距离: ";
std::cin >> longDistance;
std::cout << "转换为码为: "<<longDistance * 220 << " " << "码";
return 0;
}
三、第三题
题目:编写一个C++程序,它使用3个用户定义的函数(包括maiin()),并生成下面的输出:
Three blind mice
Three blind mice
See how they run
See how they run
其中一个函数要调用两次,该函数生成前两行:另一个函数也被调用两次,并生成其余的输出。
#include <iostream>
void ThreeMice();
void SeeRun();
int main() {
ThreeMice();
ThreeMice();
SeeRun();
SeeRun();
return 0;
}
void ThreeMice() {
std::cout << "Three blind mice" << std::endl;
}
void SeeRun() {
std::cout << "See how they run" << std::endl;
}
四、第四题
题目:编写一个程序,让用户输入其年龄,然后显示该年龄包含多少个月。如下所示:
Enter your age: 29
#include <iostream>
int main() {
int ageInput;
std::cout << "请输入年龄:";
std::cin >> ageInput;
while (ageInput < 0) {
std::cout << "请正确输入这辈子的年龄:";
std::cin >> ageInput;
}
std::cout << "该年龄包括" << ageInput*12 << "个月。";
return 0;
}
五、第五题
题目:编写一个程序,其中的main()调用一个用户定义的函数
(以摄氏度值为参数,并返回相应的华氏温度值)。该程序按下面
的格式要求用户输入摄氏温度值,并显示结果:
Please enter a Celsius value: 20
20 degrees Celsius is 68 degrees Fahrenheit.
下面是转换公式:
华氏温度 = 1.8 × 摄氏温度 + 32.0
#include <iostream>
int main() {
float degreesInput;
std::cout << "Please enter a Celsius value: ";
std::cin >> degreesInput;
std::cout <<degreesInput<< " degrees Celsius is "
<<1.8*degreesInput + 32.0 <<" degrees Fahrenheit.";
return 0;
}
六、第六题
题目:编写一个程序,其main()调用一个用户定义的函数(以光年值为参数,并返回对应天文单位的值)。该程序按下面的格式要求用户输入光年值,并显示结果:
Enter the number of light years: 4.2
4.2 light years = 256608 astronmical units.
1光年=63240天文单位
#include <iostream>
double LightUnits(double lightYears_);
int main() {
double lightYears;
std::cout << "Enter the number of light years: ";
std::cin >> lightYears;
std::cout << lightYears << " light years = " << LightUnits(lightYears) << " astronmical units.";
return 0;
}
double LightUnits(double lightYears_) {
return lightYears_ * 63240;
}
七、第七题
题目:编写一个程序,要求用户输入小时数和分钟数,在main()函数中,将着两个值传递给一个void()函数,后者以下面这样的格式显示这两个值:
Enter the number of hours: 9
Enter the number of minutes: 28
Time: 9:28
#include <iostream>
void ShowTime(int hours_, int minutes_);
int main() {
int hours = 0;
int minutes = 0;
std::cout << "Enter the number of hours: ";
std::cin >> hours;
std::cout << "Enter the number of minutes : ";
std::cin >> minutes;
ShowTime(hours, minutes);
return 0;
}
void ShowTime(int hours_, int minutes_) {
std::cout << "Time: " << hours_ << ":" << minutes_;
}
谢谢观看,祝顺利。