关于C语言的几个问题

实验(四) 调试
验证型实验/必做
(保存电子版程序)
本部分的程序计算某年某月有几天,程序运行存在错误。请改正其中的语法错误使得程序编译成功。程序编译后,请比较输出结果与正确的实例输出,对可能存在的逻辑错误进行修改。
1. 正确的输入和输出
运行1:
enter year and month , example 1996, 5:
2006 , 5
2006 – 5 has 31 days
运行2:
enter year and month , example 1996, 5:
1996 , 2
2006 – 5 has 28 days
2. 错误的程序代码
/*debug.c*/
#include <stdio.h>
void main()
{ int year , month , days ;
printf(“\n enter year and month , example 1996, 5:\n”);
scanf(“%d %d”, &year , &month);

switch(month)
{ case 1 :
case 3 :
case 5 :
case 7 :
case 8:
case 10 :
case 12: days=31 ;
case 4: case 6: case 9 : case 11: days = 30 ;
case 2: days = 29;
default : printf(“input error!\n”)
}
printf(“%d-%d has %d days \n”, year , month , days);
}
3. 问题解决技巧
程序应对润年做出处理

第1个回答  2010-04-19
2、对于switch()中的case语句后面应该有结束语句break;
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: days = 29; break;
default : printf(“input error!\n”)
}
3、对润年的判断只要(能直接被400整除,能被4整除但不能被100整除的)就可以了。
#include <stdio.h>
void main()
{ int year , month , days ,n=0;
printf(“\n enter year and month , example 1996, 5:\n”);
scanf(“%d %d”, &year , &month);
if(year%400==0||year%10!=0&&year%4==0)
n=1;
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(n)
days = 29; break;
else
days=28;break;
}
default : printf(“input error!\n”)
}
printf(“%d-%d has %d days \n”, year , month , days);
}

由于本人机器没有c语言的检验器,请自行检验。如有错误,还请包涵!
第2个回答  2010-04-19
#include <stdio.h>
void main()
{ int year , month , days ;
printf("\n enter year and month , example 1996, 5:\n");
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; break;}
else {days=28;break;}
}
default : printf("input error!\n");
}
printf("%d-%d has %d days \n", year , month , days);
}

这样就好了~
修改完毕本回答被提问者采纳
相似回答
大家正在搜