2009-09-24 68 views
2

在下面的代码中,printf输出-0.00000。问题是什么?如果它是双倍而不是长双倍,那么它工作正常。C中的长双数据类型问题

#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); 
} 

回答

9

的长双正确print format%Lf。打开你的编译器的警告会指出立即错误:

 
$ gcc -Wall b.c -o b 
b.c:9: warning: return type defaults to `int' 
b.c: In function `main': 
b.c:11: warning: use of `ll' length modifier with `f' type character 
b.c:11: warning: use of `ll' length modifier with `f' type character 
b.c:12: warning: control reaches end of non-void function 
2
$ 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 

使用%LF的替代%LLF

2

您需要在printf声明f之前使用大写字母L,像所以:

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

我不知道为什么它是小写的长整数类型和大写的浮点。

4

long double的C格式化程序是%Lf。另外,是否有理由不使用math.h fabsl()函数而不是滚动自己的绝对值? (请注意,您的绝对值函数会保留负零的符号不变,但这对您的目的可能并不重要;标准fabsl函数通常也会更快)

0

您正在使用哪种编译器和目标平台?

例如,微软的库不支持long double(但确实允许使用格式说明符),如果你使用的是微软的编译器,这并不重要,因为long double是double的同义词,所以它没有任何东西。

如果您正在使用MinGW/GCC,您仍然在使用Microsoft的C库,但有一个80位长的双精度型。在MinGW中,最简单的解决方案是使用C++的std :: ostream,因为它使用GNU库并支持long double。

或者,您可以简单地将其转换为双倍输出。

Clifford