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

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

最近更新

  1. TCP协议是安全的吗?

    2023-12-18 18:46:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-18 18:46:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-18 18:46:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-18 18:46:05       18 阅读

热门阅读

  1. vue2源码解析---watch和computed

    2023-12-18 18:46:05       37 阅读
  2. node之mysql篇经典八小时

    2023-12-18 18:46:05       43 阅读
  3. low private exponent attack

    2023-12-18 18:46:05       45 阅读