C++程序计算给定年份的奇数天数
给定正整数n,任务是生成到给定年份n为止的奇数天数。
示例
Input-: days = 500 Output-: number of odd days are: 5 Input-: days = 400 Output-: number of odd days are: 0
如何计算给定年份的奇数天数
为了计算奇数天数,我们首先需要检查给定年份是否是闰年,因为如果是闰年,奇数天数将会发生变化。如果年份能被100或400整除但不能被4整除,则该年份为闰年,否则为平年。如果我们用总天数对7取模,即一周的天数。因此,平年包含1个奇数天,闰年包含2个奇数天。
我们在此程序中使用的方案如下 −
- 将天数作为输入输入
- 检查年份是闰年还是平年
- 通过将总天数除以模数来计算奇数天
- 显示最终结果,即从1到n的年份中的天数
算法
Start Step 1-> Declare function to calculate number of odd days in a given year int cal_odd(int days) declare int cal_1 = days / 100 declare int cal_2 = days / 400 declare int check_leap = days >> 2 declare int temp = days - check_leap IF (cal_1) set temp += cal_1 Set check_leap -= cal_1 End IF (cal_2) Set temp -= cal_2 Set check_leap += cal_2 End declare int final_days = temp + check_leap * 2 Declare int odd = final_days % 7 return odd step 2->In main() Declare int days = 500 call cal_odd(days) Stop
示例
#include <iostream> using namespace std; //calculate number of odd days in a given year int cal_odd(int days) { int cal_1 = days / 100; int cal_2 = days / 400; int check_leap = days >> 2; int temp = days - check_leap; if (cal_1) { temp += cal_1; check_leap -= cal_1; } if (cal_2) { temp -= cal_2; check_leap += cal_2; } int final_days = temp + check_leap * 2; int odd = final_days % 7; return odd; } int main() { int days = 500; cout<<"number of odd days are : "<<cal_odd(days); return 0; }
输出
number of odd days are : 5
广告