Shinz6
Shinz6

Reputation: 147

Why does the `sqrt()` print the desired output when I use `float`s instead of `double`s?

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

double hypotenuse( double side1, double side2 );

int main( void )
{
    double a, b;

    printf( "Enter the values of the two sides: " );
    scanf( "%f %f", &a, &b );
    printf( "\nThe length of hypotenuse is: %f", hypotenuse( a, b ) );   

    getchar();
    getchar();
    return 0;
}

double hypotenuse( double side1, double side2 )
{
       double c;

       c = (side1 * side1) + (side2 * side2);
       return sqrt( c );
}

The above program works when I use float a, b; instead of double a,b;. Why?

Upvotes: 1

Views: 80

Answers (2)

chux
chux

Reputation: 154302

For scanf(), the specifier "%f" expects a float * argument, not a double *.

double a;
//           v--- &a is type double *, scanf("%f" expects float *
scanf( "%f", &a );

To scan in double, use specifier "%lf" which expects a double * argument.

double a;
//            v--- &a is type double *
scanf( "%lf", &a );

Detail: The arguments to scanf() are addresses of where scanf() can store the results. A float * is not the same as double *.

With printf(), numeric arguments are the value to print. Since printf() takes variable number of arguments, they go through usual promotions like float to double. Thus printf("%f", some_float) and printf("%f", some_double) can use the same format specifier. Usual promotions does not apply to &a, &b with scanf() as those argument are pointers (addresses), not arithmetic values.


Note: Always good to check scanf() results. The space between "%lf" and "%lf" is not needed as "%lf" itself consumes leading white-space, yet it is often visually easier to understand.

if (2 != scanf( "%lf%lf", &a, &b )) Handle_Error();

Upvotes: 1

icecity96
icecity96

Reputation: 1227

In your code, you use

scanf( "%f %f", &a, &b );

But %f is used for a float ,not a double. Try %lf for a double.

Upvotes: 3

Related Questions