auto关键字
自动推断类型的关键字,它将会根据值来对变量设置数据类型。它不允许在声明变量时不设置默认值,必须在声明的同时为变量设置默认值。
auto关键字无法精确的指定变量的具体数据类型,所以默认值可能出现混淆时,就只能声明具体数据类型的变量。
练习题
1、让用户输入自己的身高(米),将它转换为厘米输出。
答:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
float height = 0.0f;
cout << "Enter your height in meter:";
cin >> height;
cout << "Your height in centimeter is: " << height * 100.0f <<"cm" << endl;
}
2、编写一个程序,让用户输入秒数,将他转换为天-小时-分钟-秒并打印出来。
答:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int second = 0;
cout << "Enter a second(integer):";
cin >> second;
//1h = 60m = 3600s 1d = 24h
cout << "The converted result is: "
<< second / 60 / 60 / 24<< "day(s), "
<< second / 3600 % 24<< "hour(s), "
<< second / 60 % 60<< "minute(s), "
<< second % 60<< "second(s)."<<endl;
}
3、要求用户输入一个班级的男生和女生的人数,输出女生的比例(百分比)。
答:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int male = 0;
int female = 0;
cout << "Enter the count for male in the class:";
cin >> male;
cout << "Enter the count for female in the class:";
cin >> female;
cout << "The percentage of female in the class is:"
<< (float)female / (float)(female + male) * 100.0f
<< "%." << endl;
}