Hi yes I am having some trouble with the following code. The function above executes and outputs 132.87 to the float variable but when I return this back to the main program the output is then shortened to 132.00
This is obviously something simple I am missing can anyone help me with this one please? Much appreciated.
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
In some C versions, return values & types default to int
, so by declaring your function like
calcSigmaXY(max)
you're basically saying
int calcSigmaXY(max)
ergo the loss of precision - the float
you return is converted to an int
. Declare your function as
float calcSigmaXY(max) {
//...
}
You have to declare the return value of calcSigmaXY
, otherwise the return value is 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With