第二章 开始学习C++
1,编写一个C++程序,它显示你的姓名和地址。
#include<iostream>
using namespace std;
int main()
{
cout<<"Tom"<<" "<<"English";
cout<<endl;
return 0;
}
2,编写一个C++程序,它要求用户输入一个以long为单位的距离,然后将它转换为码(一long等于220码)。
#include<iostream>
using namespace std;
int main()
{
double distance;
double yard;
cout<<"Enter a distence: "; //输入长度
cin>>distance;
cout<<endl;
yard = distance/220; //换算
cout<<distance<<" long is "<<yard<<" yard."; //输出换算后长度
cout<<endl;
return 0;
}
3,编写一个C++程序,它使用3个用户定义的函数(包括main()),并生成下面的输出:
Three blind mice
Three blind mice
See how they run
See how they run
一个函数调用两次。
#include<iostream>
using namespace std;
void Blind_mice(void);
void See_run(void); //函数声明
int main()
{
Blind_mice();
Blind_mice();
See_run();
See_run(); //引用函数
return 0;
}
void Blind_mice(void)
{
cout<<"Three blind mice"; //输出第一句
cout<<endl;
}
void See_run(void)
{
cout<<"See how they run"; //输出第二句
cout<<endl;
}
4,编写一个函数,让用户输入年龄,然后显示该年龄包含多少月,如下所示:
Enter your age: 29
#include<iostream)
using namespace std;
int main()
{
int age;
cout<<"Enter your age: ";
cin>>age; //输入年龄
cout<<"Your age are "<<age*12<<" months\n"; //输出月数
return 0;
}
5,编写一个程序,其中的main()调用一个用户定义函数(以摄氏温度值为参数,并返回相应的华氏温度值)。该程序按下面的格式要求用户输入摄氏温度值,并显示结果:
Please enter a Celsius value: 20
20 degrees Celsius is 68 degrees Fahrenheit.
#include<iostream>
using namespace std;
int main()
{
double degree;
cout<<"Please enter a Celsius value: ";
cin>>degree;
cout<<degree<<" deree Celsius is "<<degree*1.8+32.0
<<" degrees Fahrenheit.\n";
return 0;
}
6,编写一个程序,其main调用一个用户定义的函数(以光年值为参数,并返回相应天文单位的值)。该程序按下面的格式要求用户输入光年值,并显示结果:
Enter the number of light years:4.2
4.2 light years = 265608 astronomical units.
#include<iostream>
using namespace std;
int main()
{
double light_year;
cout<<"Enter the number of light years: ";
cin>>light_year;
cout<<light_year<<" ligthe years = "<<light_year*63240
<<" astronomical units.\n";
return 0;
}
7,编写一个程序,要求用户输入小时数和分钟数。在main函数中,将这两个值传递给一个void函数,后者以这种格式显示着两个值:
Enter the number of hours: 9
Enter the number of minutes: 28
time : 9:28
#include<iostream>
using namespace std;
void Time(int hour, int minute);
int main()
{
int hour,minute;
cout<<"Enter the number of hours: ";
cin>>hour;
cout<<"Enter the number of minutes: ";
cin>>minute;
Time(hour, minute);
return 0;
}
void Time(int hour, int minute)
{
cout<<hour<<":"<<minute;
}
问题:
使用cout后再使用cin,没有输入换行符也换行了。
原因:
cin不丢会弃换行符,但是 >> 会跳过换行符。于是该行中最后输入的回车符就会被保存在cin的缓冲区中,在下次输入时会首先从缓冲区中取出这个换行符 ,这就会影响下次输入。
解决办法:
方法一:
cin >> year;
cin.get();
方法二:
(cin >> year).get();