浮点数字0.1和0.5的精度如何在c中变化
How the precision for floating point numbers 0.1 and 0.5 varies in c
我附加了两个程序。我从门户网站上得到了这些程序。你能解释一下吗?
程序1:
#include<stdio.h>
int main()
{
float x = 0.4;
if (x == 0.4)
printf("n if");
printf("n sizeof(0.4) : %d sizeof(x) : %d",sizeof(0.4) , sizeof(x));
return 0;
}
程序2:
#include<stdio.h>
int main()
{
float x = 0.5;
if (x == 0.5)
printf("n if") ;
printf("n sizeof(0.5) : %d sizeof(x) : %d",sizeof(0.5) , sizeof(x));
return 0;
}
对于程序1,我得到的输出为:
sizeof(0.4) : 8 sizeof(x) :4
对于程序2,我得到的输出为:
if
sizeof(0.5) : 8 sizeof(x) :4
这两个程序的执行有什么区别?
这不是旧问题的重复。。。。
我需要解释为什么5 的xin倍数的值通过了条件
if(x == 0.4) // here you are comparing float values with double
printf("n if") ;
所以在这种情况下,隐式类型转换将在内部发生,此时float值将转换为double。(当将浮点值转换为双倍值时,它将为低32位设置0。因此条件失败(
if(x == 0.4f)
printf("n if") ; // now it will print if
通常情况下,当你给sizeof(0.4)
时,它会将0.4
视为双倍。对于浮点给出sizeof(0.4f)
,现在它将给出输出sizeof(0.4): 4
相关文章:
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- C++取消引用指针.为什么会发生变化
- 为什么在读取文件大小时文件IO速度会发生变化
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 为什么cudaMemGetInfo报告设备内存总量的变化
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 如何打印boost多精度128位无符号整数
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C 字符串返回字符串的整数/双精度/长整型值
- 如何避免LED在循环状态变化中闪烁?
- 由于在 g++ 4.4.7 的 std::vector 中使用内联函数而导致精度变化C++ 32 位20120313
- 浮点数字0.1和0.5的精度如何在c中变化
- c++中双精度值的细微变化