701人加入学习
(2人评价)
C++编程系列 第一季编程基础

制作于2018年2月7日

价格 免费
该课程属于 虚幻Unreal - A计划(一年有效期) 请加入后再学习

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;
}

 

[展开全文]

总述:
auto的原理就是根据后面的值,来自己推测前面的类型是什么。

auto的作用就是为了简化变量初始化,如果这个变量有一个很长很长的初始化类型,就可以用auto代替。

注意点:
1.用auto声明的变量必须初始化。(auto是根据后面的值来推测这个变量的类型,如果后面没有值,自然会报错)

2.函数和模板参数不能被声明为auto(原因同上)

3.因为auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作。

[展开全文]

授课教师

加我的QQ问问题:804632564

课程特色

下载资料(1)
视频(58)