笔者一边从网上视频学习C要领,一边分享下面的代码,找出float、double和long double的区别。我在运行在 64 位 Windows 10 笔记本电脑上的 Eclispse 中运行了这个程序。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
puts("Floating point type usage in C:");
// Floating point types
float floatNumber;
double doubleNumber;
long double longDoubleNumber;
// Size of floating point types
//lu - Stands for "unsigned decimal integer" and "long"
printf("Storage size for unsigned float : %lu bytes \n", sizeof(float));
printf("Storage size for double : %lu bytes \n", sizeof(double));
printf("Storage size for long double : %lu bytes \n", sizeof(long double));
floatNumber = 2.0/3.0;
doubleNumber = 2.0/3.0;
longDoubleNumber = 2.0/3.0;
puts("\nCompare precision at 4 decimal points:");
printf("floatNumber = %1.4f\n", floatNumber);
printf("doubleNumber = %1.4lf\n", doubleNumber);
printf("longDoubleNumber = %1.4Lf\n", longDoubleNumber);
puts("\nCompare precision at 10 decimal points:");
printf("floatNumber = %1.10f\n", floatNumber);
printf("doubleNumber = %1.10lf\n", doubleNumber);
printf("longDoubleNumber = %1.10Lf\n", longDoubleNumber);
puts("\nCompare precision at 30 decimal points:");
printf("floatNumber = %1.30f\n", floatNumber);
printf("doubleNumber = %1.30lf\n", doubleNumber);
printf("longDoubleNumber = %1.30g\n", longDoubleNumber);
return 0;
}
不知何故,我没有得到预期的输出。我已经添加了我在 Eclispse 控制台中得到的输出。谁能帮我弄清楚出了什么问题
Floating point type usage in C:
Storage size for unsigned float : 4 bytes
Storage size for double : 8 bytes
Storage size for long double : 16 bytes
Compare precision at 4 decimal points:
floatNumber = 0.6667
doubleNumber = 0.6667
longDoubleNumber = 0.0000 //Expected value = 0.6667
Compare precision at 10 decimal points:
floatNumber = 0.6666666865
doubleNumber = 0.6666666667
longDoubleNumber = 0.0000000000 //Expected value = 0.6666666667
Compare precision at 30 decimal points:
floatNumber = 0.666666686534881590000000000000
doubleNumber = 0.666666666666666630000000000000
longDoubleNumber = 3.1728895775924853e-317 //This is not the expected value