[C]计算某一天是该年中的第几天

输入年月份,计算今天是今年的第几天?

#include<stdio.h>  void main()  {      int year,month,day,days,i,d;      printf("请输入年,月,日:\n");      scanf("%d,%d,%d",&year,&month,&day);      days=0;      for(i=1;i<month;i++)      {          switch(i)          {              case 1:              case 3:              case 5:              case 7:              case 8:              case 10:              case 12:d=31;break;              case 4:              case 6:              case 9:              case 11:d=30;break;              case 2:if(year%4==0&&year%100!=0||year%400==0)                         d=29;                     else d=28;          }          days+=d;      }      printf("%d年%d月%d日是这一年的第%d天。\n",year,month,day,days+day);  } 

运行结果:




















本文转蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366552,如需转载请自行联系原作者

在C语言,我们可以使用if分支结构结合一些基本数学运算来计算某月某日是一第几天。这里有一个简单的算法: ```c #include <stdio.h> int is_leap_year(int year) { if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { return 1; // 是闰 } else { return 0; // 非闰 } } int days_in_month(int month, int year) { switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: if (is_leap_year(year)) { return 29; } else { return 28; } default: return -1; // 输入错误 } } int day_of_year(int day, int month, int year) { int total_days = 0; for (int i = 1; i < month; i++) { // 统计前几个月的天数 total_days += days_in_month(i, year); } total_days += day; // 加上本月的天数 if (month > 2 && is_leap_year(year)) { total_days++; // 如果是闰的二月,加一天 } return total_days; } int main() { int day, month, year; printf("请输入日期(格式:dd mm yyyy): "); scanf("%d %d %d", &day, &month, &year); if (day <= 0 || month <= 0 || month > 12 || day > days_in_month(month, year)) { printf("输入无效日期!\n"); } else { int day_of_year_value = day_of_year(day, month, year); printf("给定日期 %d/%d/%d 是当的第%d天.\n", day, month, year, day_of_year_value); } return 0; } ``` 这个程序首先判断是否为闰,然后根据月份计算前几个月的总天数,加上指定的那一天,得到全天数。请注意,此代码仅处理公历,并假设用户输入的是有效日期。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值