所以我试图使用isdigit()来检查非数值,并且由于某种原因,当我输入一个整数时,我得到一个浮动异常错误,并且我生成的printf语句“无效输入”。我很困惑为什么当我输入一个数字时它进入我的if语句,只有它不是一个整数才是真的
#include <stdio.h>
#include <ctype.h>
int main()
{
int hour=0, minute=0, total=0, maxDiveTime=0, counter=0, average=0;
printf ("Enter dive times in the format of HH:MM (hours:minutes), Enter \\0 to stop\n");
while (scanf("%d:%d",&hour, &minute) != '\0')
{
if ((!isdigit(hour)) || (!isdigit(minute)))
{
printf("Invalid Input\n");
break;
}
else
{
if (((hour*60)+minute) > (maxDiveTime))
{
maxDiveTime = ((hour*60)+minute);
}
total = total + (hour*60) + minute;
counter ++;
}
}
average = total/counter;
printf("The total divetime is %d:%d\n", total/60, total%60);
printf("The average divetime is %d:%d\n", average/60, average%60);
printf("The max divetime is %d\n", maxDiveTime );
return 0;
}
答案 0 :(得分:1)
首先,浮动异常的原因是当你第一次进入循环时或者根本没有进入循环时,表达式count
中的total/count
为零。因此在计算某些内容之前请先检查count
。其次,scanf
返回成功读入的值的数量,在您的情况下应为2
。第三,isdigit
期望一个字符,即'0'
之类的字符,而不是从0
到某事的整数。当scanf
%d
成功时,您已经成功读取了一个数字(没有别的)。
int main()
{
int hour=0, minute=0, total=0, maxDiveTime=0, counter=0, average=0;
printf ("Enter dive times in the format of HH:MM (hours:minutes), Enter \\0 to stop\n");
while (scanf("%d:%d",&hour, &minute) == 2)
{
if (((hour*60)+minute) > (maxDiveTime))
{
maxDiveTime = ((hour*60)+minute);
}
total = total + (hour*60) + minute;
counter ++;
}
if (count > 0) {
average = total/counter;
printf("The total divetime is %d:%d\n", total/60, total%60);
printf("The average divetime is %d:%d\n", average/60, average%60);
printf("The max divetime is %d\n", maxDiveTime );
}
return 0;
}