C++ primer plus (第六版) 编程练习第二章答案
//第一题
#include<iostream>
using namespace std;
int main()
{
string name, address;
cout << "请输入您的名字:";
cin >> name;
cout << "请输入您的地址:";
cin >> address;
cout << "姓名:" << name << endl;
cout << "地址:" << address << endl;
return 0;
}
//第二题
#include<iostream>
#define length_long 220
using namespace std;
int main()
{
float distance;
cout << "请输入距离(单位:long):";
cin >> distance;
cout << "转换为码后为:" << distance * length_long << endl;
return 0;
}
//第三题
#include<iostream>
using namespace std;
void show01();//函数定义
void show02();//被调用用于输出的函数
int main()
{
for (int i = 0; i < 2; i++)
{
show01();
}
for (int i = 0; i < 2; i++)
{
show02();
}
return 0;
}
void show01()
{
cout << "Three blind mice" << endl;
}
void show02()
{
cout << "See how they run" << endl;
}
//第四题
#include<iostream>
using namespace std;
int main()
{
int age;
cout << "Enter your age:";
cin >> age;
cout << "Your age in months is " << age * 12 << endl;
return 0;
}
//第五题
#include<iostream>
using namespace std;
void tem_convert(float celsius);//用于将摄氏温度转化为华氏温度
int main()
{
float celsius;//摄氏度
cout << "Please enter a Celsius value: ";
cin >> celsius;
tem_convert(celsius);//调用函数转化为华氏度
return 0;
}
void tem_convert(float celsius)
{
cout << celsius << "degrees Celsius is " << celsius * 1.8 + 32.0 << " degrees Fahrenheit.";
}
//第六题
#include<iostream>
constexpr auto ast_unit = 63240;
using namespace std;
void cal_distance(float light_year);
int main()
{
float l_year;//将要输入的光年值
cout << "Enter the number of light years:";
cin >> l_year;
cal_distance(l_year);
return 0;
}
void cal_distance(float light_year)
{
cout << light_year << " light years = " << light_year * ast_unit << " astronomical units.";
}
//第七题
#include<iostream>
using namespace std;
void show_time(int h, int m);
int main()
{
int hour, minute;
cout << "Enter the number of hours:";
cin >> hour;
cout << "Enter the number of minutes:";
cin >> minute;
show_time(hour, minute);
return 0;
}
void show_time(int h, int m)
{
cout << "Time: " << h << ":" << m << endl;
}
注:以上代码均可在VS2019中正常运行。