你可以说我对 C 比较陌生,但我需要澄清一个问题。我有一个 char[] 代表一个数字。如果这个 char[] 比 LONG_MAX 长,我想告诉用户它太长了。问题是当我将它的值与浮点数进行比较时,它会被截断。这就是我的意思。
int main(int argc, char ** argv) {
char str[] = argv[1]; /* I set it to 9223372036854775809, only +1 higher than LONG_MAX */
double l = atof(str);
double j = LONG_MAX;
printf("%lf\n", l); /* This prints 9223372036854775808.000000, which is LONG_MAX ??? WHY?? */
printf("%lf\n", j); /* This prints same as above, 9223372036854775808.000000 */
printf("%s\n", l > j ? "true" : "false"); /* false */
return 0; /* what am I doing wrong? */
}
更新:
我尝试了您的 iret 解决方案,但仍然遇到相同的舍入问题
j = LONG_MAX;
int iret = sscanf (str, "%lf", &l);
if (iret != 1)
return 0; /* conversion was bad */
else {
if (l > j || l < -(j))
return 0; /* too small or too large */
}
printf("%lf\n", l);
printf("%lf\n", j);
printf("%s\n", l > j ? "true" : "false");