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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP