I wrote a program that calculates the square root of a floating-point number using long double
precision.
#include <stdio.h>
#include <tgmath.h>
int main(void)
{
long double x;
printf("Enter a real number: ");
scanf("%Lf", &x);
//x = 2.0; //Not a scanf() problem, even with this line it still outputs 0
int precision;
printf("Enter the precision of the output (number of digits after the .): ");
scanf("%d", &precision);
printf("sqrt(%.*Lf) = %.*Lf\n", precision, x, precision, sqrt(x));
//Tried with a constant precision embedded in the string instead of the *, still prints 0
printf("Press Enter to continue . . . ");
getchar();
getchar();
}
The output is:
Enter a real number: 2
Enter the precision of the output (number of digits after the .): 5
sqrt(0.00000) = 0.00000
Press Enter to continue . . .
At first, I though it was a bug with my program. I replaced the long double
with double
and %Lf
with %lf
and it all seems to work:
#include <stdio.h>
#include <tgmath.h>
int main(void)
{
double x;
printf("Enter a real number: ");
scanf("%lf", &x);
int precision;
printf("Enter the precision of the output (number of digits after the .): ");
scanf("%d", &precision);
printf("sqrt(%.*f) = %.*f\n", precision, x, precision, sqrt(x));
printf("Press Enter to continue . . . ");
getchar();
getchar();
}
Output:
Enter a real number: 2
Enter the precision of the output (number of digits after the .): 5
sqrt(2.00000) = 1.41421
Press Enter to continue . . .
What is the reason for this?
Compiler: GCC 9.2.0 (with -std=c17
)
Platform: Windows 10 x64
UPDATE: A simple printf("%Lf\n", 2.0L);
prints 0.000000
. This means my code is not bugged.