2.7编程练习
2.编写一个C++程序,它要求用户输入一个以long为单位的距离,然后将它转换为码 (一long等于220码)
#include<iostream>
int main()
{
// 2.2 要求用户输入一个以long为单位的距离,然后将它转换为码
int abc;
std::cout << "请输入一个以long为单位的距离:";
std::cin >> abc;
std::cout << abc*220 << "码" << std::endl;
return 0;
}
3.编写一个C++程序,它使用3个用户定义的函数(包括main()),并生成下面的输出:
There blind mice
There blind mice
See how they run
See how they run
其中一个函数要调用两次,该函数生成前两行:另一个函数也被调用两次,并生成其余的输出。
//使用3个用户定义的函数
#include<iostream>
//函数()括号不填等同于函数(void)
void Three();
void See();
int main()
{
Three();
Three();
See();
See();
return 0;
}
void Three()
{
std::cout << "There blind mice" << std::endl;
}
void See()
{
std::cout << "See how they run" << std::endl;
}
4.编写一个程序,让用户输入其年龄,然后显示该年龄包含多少个月,如下所示:
Enter your age: 29
#include<iostream>
int main()
{
std::cout << "Enter your age: ";
int age;
std::cin >> age;
std::cout << "your age includes "
<< age*12 << " months." << std::endl;
return 0;
}
5.编写一个程序,其中的main()调用一个用户定义的函数(以摄氏温度值为参数,并返回相应的华氏温度值)。该程序按下面的格式要求用户输入摄氏温度值,并显示结果:
Please wnter a Celsius value: 20
20 degrees Celsius is 68 degrees Fahrenheit.
下面是转换公式:
华氏温度=1.8*摄氏温度+32.0
#include<iostream>
double CtF(double c);
int main()
{
std::cout << "Please wnter a Celsius value:";
double c;
std::cin >> c;
double f = CtF(c);
std::cout << c <<" degrees Celsius is " << f << " degrees Fahrenheit."<<std::endl;
return 0;
}
double CtF(double c) //Convert Celsius units to Fahrenheit units
{
return c*1.8+32.0;
}
6.编写一个程序,其main()调用一个用户定义的函数(以光年值为参数,并返回对应天文单位的值)。该程序按照下面的格式要求用户输入光年值,并显示结果:
Enter the number of light year:4.2
4.2 light years = 265608 astronomical units.
#include<iostream>
double LtA(double l);
int main()
{
std::cout << "Enter the number of light year:";
double l;
std::cin >> l;
double a = LtA(l);
std::cout << l <<" light years = " << a << " astronomical units."<<std::endl;
return 0;
}
double LtA(double l) //Convert light-year units to astronomical units
{
return l*63240.00;
}
7.编写一个程序,要求用户输入小时数和分钟数。在main()函数中,将这两个值传递给一个void函数,后者以下面这样的格式显示这两个值:
Enter the number of hours:9
Enter the number of minutes:28
Time 9:28
#include<iostream>
void hm(int, int);
int main()
{
int h;
int m;
std::cout << "Enter the number of hours:";
std::cin >> h;
std::cout << "Enter the number of minutes:";
std::cin >> m;
hm(h,m);
return 0;
}
void hm(int h,int m)
{
std::cout <<"Time " << h <<":" << m <<std::endl;
}