0

I am totally new to C langauge. Trying to pick up here. Hope you guys can help me a little, and sorry in advance if i asked something stupid, but i couldnt really find any answer to this specific question. also sorry for my english.

Anyway below is my code that works okay to me.

#include <stdio.h>

int main(int argc, const char * argv[])
{


// float variable named "Crit_Dmg"
float Crit_Dmg;

// give "Crit_Dmg" a value
Crit_Dmg = 11.34;


// Log it to the user
printf("Critical Damage = %f.\n", Crit_Dmg);

// Declare Float variable named "Magic_Dmg"
float Magic_Dmg;

// Give Magic_Dmg a value
Magic_Dmg = 5.48;


// Show user
printf("Magical Damage = %f.\n", Magic_Dmg);

// Declare Double variable named "T_Dmg" (Total Dmg)
double T_Dmg;

// calculation of total damage (T_Dmg)
T_Dmg = Crit_Dmg + Magic_Dmg;

// show user Totas Dmg value
printf("Total Damage = %f.\n", T_Dmg);

// end
return 0;

}

the printf result shows

Critical Damage = 11.340000.
Magical Damage = 5.480000.
Total Damage = 16.820000.
Program ended with exit code: 0

but when i increase Crit_Dmg and Magic_Dmg value higher, the mantissa just inaccurate as per my input...

for example i changed to

Crit_Dmg = 115.34;

Magic_Dmg = 515.48;

the printf appear to be as per below

Critical Damage = 115.339996.
Magical Damage = 515.479980.
Total Damage = 630.819946.
Program ended with exit code: 0

why is the mantissa doesnt appear as per my input? how do i fix it?

Deetee
  • 9
  • 1

1 Answers1

0

As others have pointed out, floats are stored in base 2 to maximise the precision of the number stored for a given amount of memory, but not all base 10 decimals have exact representations in base 2, so sometimes there will be rounding errors in base 2 which you wouldn't see in base 10, even though the overall accuracy for arbitrary numbers is better than using base 10.

Easiest fix is to format the output more explicitly:

printf("Critical Damage = %.2f.\n", Crit_Dmg);
Douglas
  • 36,802
  • 9
  • 76
  • 89