Problem with Math. h functions

Asked

Viewed 156 times

2

always receive 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;

}
  • Objective: to calculate the distance between two points in the Cartesian plane

  • 1

    This code can compile?

  • 1

    Edit your question instead of adding your question information in comments

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.

  1. The function does not wait for a pointer to the value, but rather the value itself. Use resultado in place of &resultado.

  2. The format %f gets a double, not a float in the printf (note that in the scanf he does receive a float). Use:

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

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

Always Compile with connected warnings!

0

It seems that 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;

}
  • what you changed in the code? could explain what was and why now it should work?

  • Guilherme Bernal has really explained this very well :-) %f expecting a float, and resultado was a pointer to a float. The getch also depreciated with my compiler. Guilherme Bernal points the cast to the double. This is very important, because double have a finer precision. It depends on what you want to do, but you need to be careful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.