John Lim
John Lim

Reputation: 81

Why does my output show exponential results when my data type is double?

I am trying to find the average of 3 digits : 3.5 9.6 10.2 which are floating point numbers.

However I cannot understand why my output shows such a weird number.

/* Computes pairwise averages of three numbers */

#include <stdio.h>

double average(double a , double b )
{
    return (a + b)/2 ;
}

int main (void)
{
    double x, y,z;

    printf("Enter three numbers: ");
    scanf("%g%g%g", &x,&y,&z);
    printf("Average of %g and %g : %g\n", x,y,average(x,y));
    printf("Average of %g and %g : %g\n", y,z,average(y,z));
    printf("Average of %g and %g : %g\n", x,z,average(x,z));

    return 0;
}

enter image description here

Upvotes: 1

Views: 80

Answers (1)

chux
chux

Reputation: 154169

Save your valuable time and enable all compiler warnings to catch these simple errors.

%g expects a matching float *.
%lg expects a matching double *.

double x, y,z;
// scanf("%g%g%g", &x,&y,&z);
scanf("%lg%lg%lg", &x,&y,&z);

Better code also checks the scanf() return value

if (scanf("%lg%lg%lg", &x,&y,&z) == 3) Success();

Upvotes: 2

Related Questions