Pregunta

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?

¿Fue útil?

Solución 2

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));

Otros consejos

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>.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top