アルゴリズム学習ノート (C++) - 暴力的な解決のための日付変換

年、月、日が与えられた場合、その日付に日数を加えた日付は何日になるかを計算します。

入力について:
1行目はサンプル数mを入力し、続くm行は各行に年、月、日、加算した日数を表す4つの整数を入力します。

出力について:
m 行出力、各行は「2001-01-01」のように「04d-02d-02d」の形式で出力されます。

分析:
まず現在の年の日付を計算し、経過日数を加算して「年をまたぐ」状況があるかどうかを判断し、存在する場合は年を更新し、最後に合計日数を日付に変換します。形状。

注:指定した形式での出力については、

  • %2dは幅2の整数を出力することを意味します。2桁を超える場合は実情に合わせて出力し、そうでない場合は右詰めで出力します。
  • %02d は出力フィールド幅が 2 の整数を表します。2 桁を超える場合は実際の状況に応じて出力され、それ以外の場合は 0 ~ 2 桁で埋められます。
  • %5.2f は、フィールド幅 5 の浮動小数点数を出力することを意味します。 桁数が 5 桁未満の場合、出力は右寄せされ、小数点の後の 2 桁が予約されます。
# include <cstdio>
# include <iostream>

using namespace std;

// if this year a "RUN" year
int isRunYear(int year){
    
    
	if ((year%4==0 && year%100!=0) || (year%400==0)){
    
    
		return 1;
	}
	else{
    
    
		return 0;
	}
}

// how many days in every month
int monthTable[2][13] = {
    
    {
    
    0,31,28,31,30,31,30,31,31,30,31,30,31},
						{
    
    0,31,29,31,30,31,30,31,31,30,31,30,31}};

int dayInYear[2] = {
    
    355,356};

int main(){
    
    
	int casenumber;
	cin >> casenumber;
	while(casenumber--){
    
    
		int year, month, day, moreday;
		int total = 0;
		cin >> year >> month >> day >> moreday;
		int row = isRunYear(year);
		// first compute the total day now
		for (int i=0; i < month; ++i){
    
    
			total += monthTable[row][i];
		}
		total += day + moreday;
		// plus more days and judge if the years increased
		while(total > dayInYear[isRunYear(year)]){
    
    
			total -= dayInYear[isRunYear(year)];
			year += 1;
		} 
		// renew the data
		row = isRunYear(year);
		month = 0;
		for ( ; total>monthTable[row][month]; ++month){
    
    
			total -= monthTable[row][month];
			
		}
		day = total;
		// output
		printf("%04d-%02d-%02d", year, month, day);
	}
	return 0;
}

おすすめ

転載: blog.csdn.net/m0_53327618/article/details/124513334