【问题标题】:C - strtod seems to add Digits [duplicate]C - strtod 似乎添加了数字 [重复]
【发布时间】:2016-03-09 20:11:47
【问题描述】:

我的strtod() 出现问题,它似乎添加了一些数字。我在看书

2\t5241021356985.0302\t9.09\t825.45

从文件中跳过整数 2 后,我得到以下输出

output: 5241021356985.030273  9 .090000

这是我的代码

char *input_string = (char*) calloc(filesize, sizeof (char*));
char *output_string = (char*) calloc(filesize, sizeof (char*));
char *input_end;
fgets(input_string, filesize, infile);
input_end = input_string;
int size_to_read = (int) strtof(input_string, &input_end);
char *temp_string=(char*)calloc(70,sizeof(char*)); // max double value
double temp = 0;
++input_string;
for (int i = 0; i < size_to_read; ++i) {
   temp = strtod(input_string, &input_end);
   sprintf(temp_string, "%lf\t", temp);
   strcat(output_string, temp_string);
   input_string = input_end;
   ++input_string;
}
strcat(output_string, "\0");
printf("output: %s\n", output_string);

【问题讨论】:

标签: c file io double strtod


【解决方案1】:

通常,类型 double 具有大约 16-17 个十进制数字的精度。
现在,这不是小数点后的位数——这是有效位数的总数,句号。 (这就是为什么它被称为浮动点。)

因此,您读入的数字和您打印出来的数字在第 17 位之后有所不同,这并非巧合:

 input: 5241021356985.0302
output: 5241021356985.030273
digits: 1234567890123 4567890
                 1          2

【讨论】:

    猜你喜欢
    • 2016-08-06
    • 1970-01-01
    • 2015-09-22
    • 2018-06-17
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    相关资源
    最近更新 更多