Long double data type problem in C

In the code below, printf prints -0.00000. What is the problem? If it's a double and not a long double, then it works great.

#include<stdio.h>
long double abs1(long double x) {
    if (x<0.0)
        return -1.0*x;
    else
        return x;
}

main() {
    long double z=abs1(4.1);
    printf("%llf\n",z);
}

      

+2


source to share


5 answers


The correct print format for a long double is %Lf

. Turning on your compiler warnings would immediately indicate an error:



$ gcc -Wall bc -ob
bc: 9: warning: return type defaults to `int '
bc: In function `main ':
bc: 11: warning: use of `ll 'length modifier with` f' type character
bc: 11: warning: use of `ll 'length modifier with` f' type character
bc: 12: warning: control reaches end of non-void function
+9


source


The C formatter for long double is% Lf. Also, is there a reason not to use the math.h fabsl () function instead of rolling your own absolute value? (note that your absolute value function leaves the minus zero sign unchanged, although this may not matter for your purposes, the standard fabsl function will also be faster)



+4


source


$ gcc -Wall test.c
test.c:9: warning: return type defaults to 'int'
test.c: In function 'main':
test.c:11: warning: use of 'll' length modifier with 'f' type character
test.c:11: warning: use of 'll' length modifier with 'f' type character
test.c:12: warning: control reaches end of non-void function

      

Use% Lf instead of% llf

+2


source


You need to use capital L

before f

in a statement printf

, for example:

printf("%Lf\n", z);

      

I don't know why it is lowercase for long integer type and uppercase for floating point.

+2


source


What compiler and target platform are you using?

the Microsoft library, for example, doesn't support long doubles (but does allow the format specifier) ​​if you're using the Microsoft compiler, which doesn't really matter because long double is synonymous with double, so it doesn't get you anything.

If you are using MinGW / GCC, you are still using the Microsoft C library, but have 80 bit double bit. In MinGW, the simplest solution is to use C ++ std :: ostream as it uses the GNU library and supports long double.

Alternatively, you can just make it double to output it.

Clifford

0


source







All Articles