gpt4 book ai didi

C中char数组到float转换错误

转载 作者:行者123 更新时间:2023-11-30 19:01:01 27 4
gpt4 key购买 nike

我遇到以下情况,其中我正在逐行读取文件,其中前几行(示例)如下:

0.00000000000000000, 0.00000000000000000, 0.00000000000000000, 20.00000000000000000, 0.18854095325733133
0.00000000000000000, 0.00000000000000000, 0.00000000000000000, 28.88888888888888900, 0.18861310382752311
0.00000000000000000, 0.00000000000000000, 0.00000000000000000, 37.77777777777777900, 0.18870756072971304
0.00000000000000000, 0.00000000000000000, 0.00000000000000000, 46.66666666666667100, 0.18876790723761561
0.00000000000000000, 0.00000000000000000, 0.00000000000000000, 55.55555555555555700, 0.18879081871602224

以及行的处理:

fp = fopen(fn, "r");

if (fp == NULL) {
<...>
}

while ((read = getline(&line, &len, fp)) !=-1) {
<...>
char *pt;
pt = strtok(line,",");
while (pt != NULL) {
//order: pressure, velocity, strain, temp
pnn = atof(pt); //pressure
pt = strtok(NULL, ",");

vrm = atof(pt); //velocity
pt = strtok(NULL, ",");

epx = atof(pt); //elastic strain
pt = strtok(NULL, ",");

temp = atof(pt); //temperature
pt = strtok(NULL, ",");

//reference friction coefficient
REAL ref_ffric = (REAL)atof(pt);
ref_fric = &ref_ffric;
pt = strtok(NULL, ",");

REAL在此上下文中定义为 float

但是ref_fric从来都不是正确的数量,即第一行应该是 0.18854095325733133,但是当我打印出来时,它是 0.18854095041751862。

如何解决这个 char* 到 float 转换精度问题?

最佳答案

浮点型并不是完全精确,小数值的输出方式可能与输入时的方式不同。如果您可以使用 double 型,则更好。请参阅此相关问题:请参阅此相关问题:'float' vs. 'double' precision

关于C中char数组到float转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58627731/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com