首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

请评价一上这段代码

2012-08-01 
请评价一下这段代码题目:给出年月日,算出当天是这一年的第几天.#include stdio.hint main(){int year,mo

请评价一下这段代码
题目:给出年月日,算出当天是这一年的第几天.


#include <stdio.h>

int main()
{
int year,month,day
//输入年月日
printf("输入年月日,以空格隔开即可");
scanf("%d%d%d",&year,&month,&day);
//计算天数
switch( month-1 )
{
  case 12: day+=31;
  case 11: day+=30;
  case 10: day+=31;
  case 9: day+=30;
  case 8: day+=31;
  case 7: day+=31;
  case 6: day+=30;
  case 5: day+=31;
  case 4: day+=30;
  case 3: day+=31;
  //闰年判定
  case 2: day += (year%4==0 && year%100!=0 || year%400==0) ? 29 : 28;
  case 1: day+=31
  default: break;
}
 
//输出结果
printf("这是今年第%d天",day);
}

[解决办法]
少了输入的合法性检测!
[解决办法]

C/C++ code
#include <stdio.h>int main(void){    int y, m, d, i, days = 0;    int months[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 };    scanf("%d%d%d", &y, &m, &d);    if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))        ++months[1];    for (i = 0; i < m - 1; ++i)        days += months[i];    days += d;    printf("%d", days);    return 0;}
[解决办法]
探讨
这是在被要求用switch做出这题写的.

修复如下:
#include <stdio.h>

int main()
{
int year,month,day;
//输入年月日
while(TRUE)
{
printf("输入年月日,以空格隔开即可");
scanf("%d%d%d",&amp;year,&amp;month,&amp;day);
if( mo……

[解决办法]
探讨

引用:

依题意来看,这代码根本就错了嘛。


"当天"这个词看来有歧义?可题目就是这么说的,可以指输入的日期,也可以指程序运行的当天,我认为是前一种意思.

[解决办法]
C/C++ code
//计算天数switch( month-1 ){  case 10:  case 12:   case 8:  case 7:  case 5:  case 3:  case 1:      day+=31;      break;  case 11:  case 9:  case 6:  case 4:       day+=30;      break;  //闰年判定  case 2:       day += (year%4==0 && year%100!=0 || year%400==0) ? 29 : 28;      break;  default:       break;}
[解决办法]
switch没必要吧
C/C++ code
#include <stdio.h>int main(){    int y,m,d,ms[]={0,31,28,31,30,31,30,31,31,30,31,30,31},ds[]={0,0,31,59,90,120,151,181,212,243,273,304,334};    goto BEGIN;    AGAIN:    printf("Illegal date! Please input again!\n");BEGIN:    printf("Please input a date(format: 2012-7-19): ");    scanf("%d-%d-%d", &y, &m, &d);    if(0 >= m)                        goto AGAIN;    if(12 < m)                        goto AGAIN;    if(ms[m]+((0==y%4)&&(2==m)) < d)goto AGAIN;        printf("The day of the year is: %d.\n", ds[m]+d+((0==y%4)&&(2<m)));    return 0;} 

热点排行