C程序不能正确添加浮点数 [英] C program not adding float correctly
问题描述
float * mutate(float * organism){
int一世;
浮点数= 1;
static float newOrg [INPUTS] = {0};
(i = 0; i if(rand()%2 == 0){
sign = 1;
} else {
sign = -1;
}
float temp =(organism [i] + sign);
printf(bf:%f af:%f diff:%f sign:%f sign2:%f temp:%f\\\
\\\
,
organism [i],(organism (有机体[i] +符号) - 有机体[i],
符号,符号+符号,温度);
newOrg [i] =有机体[i] +符号;
}
return newOrg;
当 sign
是不是0,前两个%f
s是相同的,第三个是0,也把总和放在一个变量中并没有帮助。这让我感到困惑!
输出:
bf :117810016.000000 af:117810016.000000 diff:0.000000 sign:1.000000 sign2:2.000000 temp:117810016.000000
$ b
一个典型的 使用像 如果代码要保留使用 也许可以使用整数类型来完成这个任务,比如 I have a method that looks like this: When Output:
Finite precision of A typical Using a higher precision type like If code is to retain using Perhaps can code simply use integer types for this task like 这篇关于C程序不能正确添加浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! code>只能表示大约2 <32>个不同的数字。 117,810,016.0和1.0是其中两个。 117,810,017.0不是。因此,
117810016.0 + 1.0
的C总和得到了 117810016.0
的最佳答案。
$ b double
这样的更高精度的类型往往会扩展+1精确数学的范围,但即使这样也不够精确(通常约为9.0 * 10e 15或2 53)。
float
,建议限制有机体[i]
为包含范围的值或±8,388,608.0(2 23
long long
。float * mutate(float* organism){
int i;
float sign = 1;
static float newOrg[INPUTS] = {0};
for (i = 0;i<INPUTS;i++){
if (rand() % 2 == 0) {
sign = 1;
} else {
sign = -1;
}
float temp = (organism[i] + sign);
printf("bf: %f af: %f diff: %f sign: %f sign2: %f temp: %f\n\n",
organism[i], (organism[i] + sign), (organism[i] + sign)-organism[i],
sign, sign+sign, temp);
newOrg[i] = organism[i] + sign;
}
return newOrg;
}
sign
is not 0 the first two "%f"
s are the same and the 3rd is 0, also putting the sum in a variable didn't help. This is baffling me! I can post full code if needed.bf: 117810016.000000 af: 117810016.000000 diff: 0.000000 sign: 1.000000 sign2: 2.000000 temp: 117810016.000000
float
.float
can only represent about 232 different numbers. 117,810,016.0 and 1.0 are two of them. 117,810,017.0 is not. So the C sum of 117810016.0 + 1.0
results in the "best" answer of 117810016.0
.double
often will extend the range of +1 exact math, but even that will not be exact with large enough values (typically about 9.0*10e15 or 253).float
, suggest limiting organism[i]
to values to the inclusive range or ±8,388,608.0 (223).long long
.