Problem with math.h functions

2

I always get as a result: 0.000000

#include<stdio.h>
#include<math.h>

int main()

{

   float x1, y1, x2, y2, resultado;

   printf("insira x1:");
   scanf("%f", &x1);
   printf("insira y1:");
   scanf("%f", &y1);
   printf("insira x2:");
   scanf("%f", &x2);
   printf("insira y2:");
   scanf("%f", &y2);

   resultado = sqrtf((powf((x2 - x1), 2)) + (powf((y2 - y1), 2)));

   printf("resultado:");
   printf("%f\n", &resultado);

   printf("pressione qualquer tecla para sair.");
   getch();

   return 0;

}
    
asked by anonymous 14.03.2014 / 01:43

2 answers

7

The calculation is correct, your problem is just in time to display the value on the screen. When compiling the code I have the following warning:

   a.c : In function main : a.c:22:4 : warning : format %f expects argument of type double , but argument 2 has type float * -Wformat= ]

printf("%f\n", &resultado);
    ^

Two clear mistakes here.

  • The function does not expect a pointer to the value, but the value itself. Use resultado instead of &resultado .

  • The format %f gets a double , not a float in printf (note that in scanf it actually gets float ). Use:

    printf("%f\n", (double)resultado);
    

    Or better yet, declare all your variables double and use %lf in scanf .

  • Always compile with linked warnings!

        
    14.03.2014 / 01:56
    0

    It seems like the code has some basic problems. How about?

    #include<stdio.h>
    #include<math.h>
    
    int main()
    
    {
    
        float x1, y1, x2, y2, resultado;
    
        printf("insira x1:");
        scanf("%f", &x1);
        printf("insira y1:");
        scanf("%f", &y1);
        printf("insira x2:");
        scanf("%f", &x2);
        printf("insira y2:");
        scanf("%f", &y2);
    
        resultado = sqrtf((powf((x2 - x1), 2)) + (powf((y2 - y1), 2)));
    
        printf("resultado:");
        printf("%f\n", resultado);  // aqui
    
        return 0;
    
    }
    
        
    14.03.2014 / 01:56