Returning a float variable loses its precision in C

Hi, yes, I have some problems with the following code. The function above executes and returns 132.87 for the float variable, but when I return it back to the main program, the result is then reduced to 132.00

This is obviously something simple that I am missing, can someone help me with this, please? Very grateful.

calcSigmaXY(max) { int count= 0; float runTotal = 0, product[max]; for (count = 1; count <= max; count++) { product[count] = pointData[count][1] * pointData[count][2]; runTotal = runTotal + product[count]; } printf("\nruntotal is %4.2f",runTotal); // outputs 132.87 return(runTotal); } int maxPoints = 6; float sigmaXY = 0, sigmaXY = calcSigmaXY(maxPoints); printf("\nsigmaxy set to : %4.2f\n", sigmaXY); // outputs 132.00 
+4
source share
2 answers

In some versions of C, the return values ​​and types are int by default, therefore, declaring your function as

 calcSigmaXY(max) 

you basically say

 int calcSigmaXY(max) 

ergo loss of precision - the returned float converted to int . Declare your function as

 float calcSigmaXY(max) { //... } 
+10
source

You must declare the return value calcSigmaXY , otherwise the return value will be int implicitly.

If you declare your function as float calcSigmaXY , it should work as intended.

Also consider enabling and reading warnings in your compiler / IDE.

+2
source

All Articles