Reputation: 83
I tried to implement the following calculation:
#include <stdio.h>
#include <math.h>
int main(){
float sum = 0;
int c = -4;
float x1 = 136.67;
float x2 = 2.38;
sum = c / (pow(abs(x1 - x2), 2));
printf("%f %f %f",sum,x1,x2);
return 0;
}
But the value of sum
after the execution turns out to be -4. What is wrong?
Upvotes: 0
Views: 79
Reputation: 263317
abs
is declared in <stdlib.h>
. It takes an int
argument and returns an int
result.
The missing #include <stdlib.h>
is likely to cause problems as well. You're calling abs
with a floating-point argument; without a visible declaration, the compiler will probably assume that it takes a double
argument, resulting in incorrect code. (That's under C90 rules; under C99 rules, the call is a constraint violation, requiring a compile-time diagnostic.)
You want the fabs
function defined in <math.h>
.
Upvotes: 2
Reputation: 33521
abs
expects an integer, and you are providing a float
. It should work if you apply an explicit type cast:
sum = c / (pow(abs((int)(x1 - x2)), 2));
Upvotes: 0