C Primer Plus 例子6.5中的小问题
程序清单6.5 compflt.c是比较浮点数是否相等的例子。
原程序如下:
// cmpflt.c -- 浮点数比较
#include <math.h>
#include <stdio.h>
int main(void)
{
const double ANSWER = 3.14159;
double response;
printf("What is the value of pi?\n");
scanf("%lf", &response);
while (fabs(response - ANSWER) > 0.0001)
{
printf("Try again!\n");
scanf("%lf", &response);
}
printf("Close enough!\n");
return 0;
}
在while循环中输入的时候,如果输入非数字的字符,则会陷入死循环。
我重新修改了一下,修改后的程序如下:
// cmpflt.c -- 浮点数比较
#include <math.h>
#include <stdio.h>
int main(void)
{
const double ANSWER = 3.14159;
int status = 0;
double response;
printf("What is the value of pi?\n");
status = scanf("%lf", &response);
while (fabs(response - ANSWER) > 0.0001 && status == 1)
{
printf("Try again!\n");
status = scanf("%lf", &response);
}
if (status == 1)
printf("Close enough!\n");
else
printf("You input a wrong char.\n");
return 0;
}
仍然有问题,如果输入字符,比如"w",则比较过程直接结束了。较好的方法应该是在while循环内假如if判断语句。

浙公网安备 33010602011771号