更新时间:2023-11-29 08:17:16
既然你已经在你的价值双击
,你可以检查它是否是的范围之外浮动
:
Since you have your value in a double
, you can just check if it's outside of the range of float
:
#include <stdlib.h>
#include <stdio.h>
#include <float.h>
int main(int argc, char *argv[])
{
double d = FLT_MAX;
if (argc > 1) {
d = strtod(argv[1], NULL);
}
if ((d > 0 && (d > FLT_MAX || d < FLT_MIN))
|| (d < 0 && (d < -FLT_MAX || d > -FLT_MIN)))
printf("Invalid float: %g\n", d);
else
printf("Valid: %g\n", d);
return EXIT_SUCCESS;
}
运行程序:
$ ./a.out
Valid: 3.40282e+38
$ ./a.out 3.5e38
Invalid float: 3.5e+38
$ ./a.out -1e40
Invalid float: -1e+40
您可能会或可能不会需要添加一个测试为正确的关于strtod()
回归,这取决于是否有溢出的可能性双
键入为好。
You may or may not need to add a test for correct strtod()
return, depending upon whether there's a possibility of an overflow in double
type as well.