Christian - 1 year ago 101

C Question

I am aware of floating points in C not being very precise. But I have a sniplet where I do not understand why I am getting such results.

First, if I do the calculate within one line I am getting a wrong "0" as result.

Just if I split the same calculations into several commands I am getting nearly what I would expect.

So first questions:

- Why is the single line different from the split lines?
- Is there any way how to calculate in a more precise way? I mean, 320-(10.44*4) should be 278.24 and not 278.23999! I understand rounding issues at number like roots or pi or so. But not in above example.

Ok, here is my code (minimized sniplet):

`#include <math.h>`

#include <stdio.h>

float kurv_steil,

kurv_korr,

t_abl_s,

t_out,

t_abl_s,

b,

t_tank_s;

void main()

{

t_tank_s=32;

kurv_steil=0.85;

kurv_korr=-5;

t_out=1.44;

t_abl_s=24;

printf("Werte: k_steil: %f k_korr: %f t_out: %f t_abl_s: %f\n",kurv_steil,kurv_korr,t_out,t_abl_s);

b= pow(t_abl_s,(t_out/(320-(t_out*4) )))*0.65*kurv_steil*b*(-t_out+20);

printf("[temp] Ganze Rechnung tank_s: %f\n",b);

b=320-(t_out*4);

printf("[temp] 320-(t_out*4) b: %f\n",b);

b=t_out/b;

printf("[temp] t_out/b b: %f\n",b);

b=pow(t_abl_s,b);

printf("[temp] t_abl_s^b b: %f\n",b);

b=0.65*kurv_steil*b;

printf("[temp] 0.65*kurv_steil*b b: %f\n",b);

b=b*(-t_out+20);

printf("[temp] b*(-t_out+20) b: %f\n",b);

b=2*b+t_abl_s+kurv_korr;

printf("[temp] 2*b*(-t_abl_s) b: %f\n",b);

}

Output is:

`Werte: k_steil: 0.850000 k_korr: -5.000000 t_out: 1.440000 t_abl_s: 24.000000`

[temp] Ganze Rechnung tank_s: 0.000000

[temp] 320-(t_out*4) b: 314.239990

[temp] t_out/b b: 0.004582

[temp] t_abl_s^b b: 1.014670

[temp] 0.65*kurv_steil*b b: 0.560605

[temp] b*(-t_out+20) b: 10.404831

[temp] 2*b*(-t_abl_s) b: 39.809662

I would expect to have the first output have the same value of "39.809662", but it always has "0". Why?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

as told above the problem is in formula you use. You have `b=... *b*...`

. The `b`

has unknown value by this moment (most likely compiler set it to 0) so you have `b=...*0*...`

which makes end result has 0 value.

Also you should add `2* ... + t_abl_s+kurv_korr`

to your formula

So the formula will looks like

```
b= 2 *
pow(t_abl_s,(t_out/(320-(t_out*4) ))) *
0.65 * kurv_steil *
(-t_out+20) +
t_abl_s + kurv_korr;
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**