【发布时间】:2017-03-07 13:49:38
【问题描述】:
为以下代码输入大数字会导致scanf 成功,尽管该值未正确存储。
printf("\nDouble max: %f\n", DBL_MAX);
printf("\nFloat max: %f\n", FLT_MAX);
printf("\nPlease insert root1 data: ");
float input1;
scanResult = scanf("%f", &input1);
printf("\nScan Result is %d\n", scanResult);
double input2;
printf("\nPlease insert root2 data: ");
scanResult = scanf("%lf", &input2);
printf("\nScan Result is %d\n", scanResult);
printf("%f", input1);
printf("%f", input2);
输出:
Double max: 17976931348623157000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000
0.000000
Float max: 340282346638528860000000000000000000000.000000
Please insert root1 data: 1872389723948273985723984756982375698374568
Scan Result is 1
Please insert root2 data: 928734812348721834.2348275
Scan Result is 1
1.#INF00
928734812348721790.000000
所以我的问题是:
第一次扫描:为什么
scanf仍然说扫描结果是1,而你可以看到该值没有正确存储?第二次扫描:为什么会这样舍入,我该如何解决?
一般而言:我们可以看到,通过 0 的数量,
DBL_MAX和FLT_MAX比我给出的输入要大得多。那么为什么它不能正确存储输入呢?
【问题讨论】:
-
你需要一本更好的
c书(或网站) -
@KevinDTimm 我可以理解为什么吗?
-
+1 关于 scanf() 溢出处理的有趣问题。它不仅抵消了您在验证输入时缺乏勤奋;-)。
-
因为没有书或网站会指示您声明浮点变量,并且他们尝试使用
printf()的形式。 (注意:您已经编辑了帖子,因此绝对错误的版本不再可见) -
正如我之前写的,它是从一个从 void* 转换它的函数复制而来的。
标签: c floating-point double scanf numeric-limits