C++编程学习(第32天)

用typedef声明新的类型名

用typedef声明一个新的类型名来代替已有的类型名。如

typedef int INTEGER;    //指定用标识符INTEGER代表int类型
typedef float REAL;    //指定用REAL代表float类型

也可以对一个结构体类型声明一个新的名字

typedef struct    //在struct之前使用了关键字typedef,表示是声明新类型名
{int month;
int day;
int year;
}DATE;            //DATE是新类型名,而不是结构体变量名

需要注意的是

1、用typedef声明的新类型名又称为typedef类型名,或typedef名字。

2、用typedef只是对已存在的类型增加一个类型名,而没有创造新的类型。

3、可以用typedef声明新类型名,但不能用来定义变量。

4、用typedef可以声明数组类型、字符串类型,使用比较方便

5、使用typedef类型名,有利于程序的通用与移植。

自定义数据类型总结

例:定义一个结构体变量,包含年月日,编写程序,要求输入年月日,程序能计算并输出该日在本年的第几天,需要注意闰年情况。

#include <iostream>
using namespace std;

struct Date
{
	int year;
	int month;
	int day;
}date;

bool isLeapYear(int year)
{
	if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
		return true;
	else
		return false;
}

int dayOfYear(Date date)
{
	int count = 0;
	int dayInMonth[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
	if (isLeapYear(date.year))
		dayInMonth[1] = 29;
	for (int i = 0; i < date.month - 1; i++)
		count += dayInMonth[i];
	count += date.day;
	return count;
}

int main()
{
	cout << "请输入年份:";
	cin >> date.year;
	cout << "请输入月份:";
	cin >> date.month;
	if (date.month < 1 || date.month>12)
	{
		cout << "月份数据错误,请重新输入!";
		return 0;
	}
	cout << "请输入日期:";
	cin >> date.day;
	if (date.day < 1 || date.day>31)
	{
		cout << "日期数据错误,请重新输入!";
		return 0;
	}
	int day = dayOfYear(date);
	cout << date.year << "年" << date.month << "月" << date.day << "日是当年的第 " << day << " 天!" << endl;
	return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武当豆豆

为国家GDP快速增长做贡献

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值