第二章 编程练习
1.编写一个C++程序,它显示您的姓名和地址。
//编写一个显示我的姓名和地址的代码
#include <iostream>
int main()
{
using namespace std;
cout <<"我的姓名是***。"<<endl;
cout <<"我家在**省**市**市"<<endl;
cin.get();
return 0;
}
2.用户输入一个以long为单位的距离,然后将它转换为码(1long=220码)。
#include <iostream>
int stonetolb(int);
int main()
{
using namespace std;
cout << "Enter the distance in long:";
int Long;
cin >> Long;
int codes = stonetolb(Long);
cout << Long <<"long=";
cout << codes <<"codes."<<endl;
cin.get();
cin.get();
return 0;
}
int stonetolb(int worden)
{
return 220 * worden;
}
3.使用三个用户定义函数产生输出。
#include <iostream>
void myfirst();
void mysecond();
using namespace std;
int main ()
{
myfirst();
myfirst();
mysecond();
mysecond();
cin.get();
return 0;
}
void myfirst()
{
cout<< "Three blind mice"<<endl;
}
void mysecond()
{
cout<<"See how they run"<<endl;
}
4.编写一个程序,让用户输入其年龄,然后显示该年龄包含多少个月。
//用户输入年龄,输出包含多少个月
#include<iostream>
int myfunc(int);
int main()
{
using namespace std;
cout <<"Enter your age:";
int age;
cin >> age;
int func = myfunc(age);
cout <<"这个年龄包含了 "<<func<<" 个月。"<<endl;
cin.get();
cin.get();
}
int myfunc(int n)
{
return 12*n;
}
5.编写一个程序,其中的main()调用一个用户定义的函数(以摄氏温度值为参数,并返回相应的华氏温度值)
该程序按下面的格式要求用户输入摄氏温度值,并显示结果:
Please enter a Celsius value: 20
20 degrees Celsius is 68 degrees Fahrenheit.
#include <iostream>
double stonetolb(double);
int main()
{
using namespace std;
cout << "Please enter a Celsius value:";
double Celsius;
cin >> Celsius;
double Fahrenheit = stonetolb(Celsius);
cout << Celsius <<" degrees Celsius is "<<Fahrenheit <<" degrees Fahrenheit"<<endl;
cin.get();
cin.get();
return 0;
}
double stonetolb(double sts)
{
return sts*9/5 + 32;
}
6.编写一个程序,其main()调用一个用户定义的界面(以光年为参数,并返回对应天文单位的值)。
该程序按下面的格式要求用户输入光年值,并返回结果:(1光年= 63240 天文单位)。
Enter the number of light years: 4.2
4.2 light years = 265608 astronomical units.
//习题6:光年和天文单位的换算
#include <iostream>
double stonetolb(double);
int main()
{
using namespace std;
cout << "Enter the number of light years:";
double light;
cin >> light;
double astronomical = stonetolb(light);
cout << light <<" light years = ";
cout << astronomical <<" astronomical units."<<endl;
cin.get();
cin.get();
return 0;
}
double stonetolb(double worden)
{
return 63240* worden;
}
7.编写一个程序,要求用户输入小时数和分钟数吗,在main()函数中,将这两个值传递给一个void函数,后者以下面这样的格式显示这两个值:
Enter the number of hours: 9
Enter the number of minutes: 28
Time: 9:28
//第7题:显示时间,两个函数
#include<iostream>
void myfunc(int m ,int n);
using namespace std;
int main()
{
cout <<"Enter the number of hours:";
int a;
cin >>a;
cout <<"Enter the number of minuters:";
int b;
cin>>b;
myfunc(a,b);
cin.get();
cin.get();
return 0;
}
void myfunc(int m,int n)
{
cout<<"Time:"<<m<<":"<<n<<endl;
}