switch语句应用例题
生活随笔
收集整理的這篇文章主要介紹了
switch语句应用例题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
問題
代碼
解析
問題
輸入某年某月某日,輸出該日是這一年的第多少天。
代碼
#include<stdio.h> int main() {int day, month, year, s = 0;printf("請輸入年月日并用逗號隔開\n");scanf("%d,%d,%d", &year, &month, &day);switch (month) {case 12:s += 30;case 11:s += 31;case 10:s += 30;case 9:s += 31;case 8:s += 31;case 7:s += 30;case 6:s += 31;case 5:s += 30;case 4:s += 31;case 3:s += 28;case 2:s += 31; case 1:s += day;break;}if (((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) && (month > 2)) //判斷是不是閏年s++;printf("這一天是這一年的第%d天", s);return 0; }運行結果是:
請輸入年月日并用逗號隔開 2022,10,19 這一天是這一年的第292天 -------------------------------- Process exited after 12.34 seconds with return value 0 請按任意鍵繼續. . .解析
? 該題首先需要判斷輸入的年份是平年還是閏年,可根據閏年的判斷依據即是否能被4整除且不能被100整除或者能被400整除,代碼表示為:
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)想要判斷一天是一年當中的第幾天,就需要把當月之前的月份天數都加起來,然后加上當月的號數由于switch語句是從上往下依次運行,因此第一個case從12開始并依次遞減到1會使程序簡便。(case1開始遞增也可以不過較復雜)switch運行代碼表示為:
switch (month) {case 12:s += 30;case 11:s += 31;case 10:s += 30;case 9:s += 31;case 8:s += 31;case 7:s += 30;case 6:s += 31;case 5:s += 30;case 4:s += 31;case 3:s += 28;case 2:s += 31; case 1:s += day;break;}第一次寫博客,如有錯誤歡迎指出
總結
以上是生活随笔為你收集整理的switch语句应用例题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Arch Linux中的Pacman命令
- 下一篇: 职场Word使用技巧大全,太实用了