gpt4 book ai didi

c - C 中 long double 的格式说明符 %Lf 未按预期工作

转载 作者:行者123 更新时间:2023-11-30 17:01:16 24 4
gpt4 key购买 nike

作者在通过网上视频学习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

最佳答案

我建议您进行一些更正,然后重新运行测试。首先,我们需要确保所有类型都是正确的,并且不涉及促销或其他事情。我们需要改变

floatNumber = 2.0/3.0;
longDoubleNumber = 2.0/3.0;

floatNumber = 2.0f / 3.0f;
longDoubleNumber = 2.0L / 3.0L;

这是禁止将结果提升为 double 所必需的(在第一种情况下,在第二种情况下从 double 类型转换为 long double),因为最初在每种情况下,两个操作数都是“double”类型。

其次,你应该摆脱未定义的行为

printf("longDoubleNumber = %1.30g\n", longDoubleNumber);

并在格式字符串中使用适当的长双长度说明符。它看起来像这样:

printf("longDoubleNumber = %1.30Lg\n", longDoubleNumber);

将结果通知我们。

关于c - C 中 long double 的格式说明符 %Lf 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37152565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com