C#问题:根据用户输入的月份和年份输出该月的天数,用函数完成。

1个回答
展开全部
摘要 亲,很高兴为您解答。下面是一个基于C#的函数来计算指定年份月份的天数:static int GetMonthDays(int year, int month) { int monthDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: monthDays = 31; break; case 4: case 6: case 9: case 11: monthDays = 30; break; case 2: if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { monthDays = 29; } else { monthDays = 28; } break; } return monthDays; }csharp
咨询记录 · 回答于2023-03-28
C#问题:根据用户输入的月份和年份输出该月的天数,用函数完成。
亲,很高兴为您解答。下面是一个基于C#的函数来计算指定年份月份的天数:static int GetMonthDays(int year, int month) { int monthDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: monthDays = 31; break; case 4: case 6: case 9: case 11: monthDays = 30; break; case 2: if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { monthDays = 29; } else { monthDays = 28; } break; } return monthDays; }csharp
这个函数中,我们使用了一个 switch 语句来判断每个月有多少天。其中,1、3、5、7、8、10、12 月份每个月都有31天,4、6、9、11月份每个月都有30天,而对于2月份,我们需要根据当前年份来判断是否为闰年。如果是闰年,则2月份有29天,否则为28天。你可以在主函数中调用这个函数来计算指定月份和年份的天数。例如:int year = 2022;int month = 2;int days = GetMonthDays(year, month);Console.WriteLine($"Year {year}, Month {month} has {days} days.");上述代码将输出 "Year 2022, Month 2 has 28 days"。
亲,这样写#include int main(){ int year,month,days,flag=1; printf("请输入年份和月份:"); scanf("%d,%d",&year,&month); switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days=31; break; case 4: case 6: case 9: case 11: days=30; break; case 2: if(year%4==0&&year%100!==0||year%400==0) days=29; else days=28; default: flag=0; } if(flag=0) printf("月份值输入错误!\n"); else printf("%d年%d月有%d天!\n",year,month,days); return 0;}
亲,;}使用该函数计算2011年5月的天数,需要调用该函数并传入参数2011和5,代码如下:int year = 2011;int month switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: monthDays = 31; break; case 4: case 6: case 9: case 11: monthDays = 30; break; case 2: if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) monthDays =
monthDays = 29; else monthDays = 28; break; default: Console.WriteLine("Invalid Month!"); break; } return monthDays;}使用该函数计算2011年5月的天数,需要调用该函数并传入参数2011和5,代码如下:int year = 2011;int month = 5;int days = GetMonthDays(year, month);Console.WriteLine("{0}年{1}月有{2}天", year, month, days);该代码将输出以下结果:2011年5月有31天 = 5;int days = GetMonthDays(year, month);Console.WriteLine("{0}年{1}月有{2}天", year, month, days);该代码将输
该代码将输出以下结果:2011年5月有31天 = 5;int days = GetMonthDays(year, month);Console.WriteLine("{0}年{1}月有{2}天", year, month, days);该代码将输出以下结果:2011年5月有31天
下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消