C++ //习题 7.2 写一个函数days,实现上面的计算。由主函数将年、月、日传递给函数days,计算后将日子数传回主函数输出。

2023-12-18 17:24:22

C++程序设计 (第三版) 谭浩强 习题7.2

习题 7.2 写一个函数days,实现上面的计算。由主函数将年、月、日传递给函数days,计算后将日子数传回主函数输出。

IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。

?

代码块
方法:使用指针,结构体,自定义类型,函数的模块化设计,分配内存
#include <iostream>
using namespace std;

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

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

bool isRightMonth(int month){
	return month < 1 || month > 12 ? false : true;
}

bool isRightDay(int year, int month, int day){
	if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month ==12){
		return day >= 1 && day <= 31 ? true : false;
	}
	else if(month == 4 || month == 6 || month == 9 || month == 11){
		return day >= 1 && day <= 30 ? true : false;
	}
	else{
		if(isLeapYear(year) == true){
			return day >= 1 && day <= 29 ? true : false;
		}
		else{
			return day >= 1  && day <= 28 ? true : false;
		}
	}
}

void inputDate(Date *date){
	cout<<"Enter Year: ";
	cin>>date->year;
	while(date->year <= 0 || date->year > 9999){
		cout<<"Year Error! Retry!\nEnter Year: ";
		cin>>date->year;
	}

	cout<<"Enter Month: ";
	cin>>date->month;
	while(isRightMonth(date->month) == false){
		cout<<"Month Error! Retry!\nEnter Month: ";
		cin>>date->month;
	}

	cout<<"Enter Day: ";
	cin>>date->day;
	while(isRightDay(date->year, date->month, date->day) == false){
		cout<<"Day Error! Retry!\nEnter Day: ";
		cin>>date->day;
	}
	cout<<endl;
}

int days(Date *date){
	int sum = 0;
	for(int i = 1; i < date->month; i++){
		if(i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i ==12){
			sum += 31;
		}
		else if(i == 4 || i == 6 || i == 9 || i == 11){
			sum += 30;
		}
		else{
			if(isLeapYear(date->year) == true){
				sum += 29;
			}
			else{
				sum += 28;
			}
		}
	}
	sum += date->day;
	return sum;
}

int main(){
	Date *date = new Date;

	inputDate(date);
	cout<<"The day is No."<<days(date)<<" days in "<<date->year<<"."<<endl;

	delete(date);

	system("pause");
    return 0;
}

文章来源:https://blog.csdn.net/navicheung/article/details/135064039
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。