有人能帮我解释为什么x2输出为0吗?我猜是因为浮点数表示方式对X1进行了舍入,是否有方法可以保留精度。
long double x1, x2;
x1= 0.087912088; // Note: 360/4095 = 0.087912088
x2 = 360/4095;
printf("%Lf, %Lf \n",x1, x2);
结果:
x1 =0.087912
x2= 0.000000
有人能帮我解释为什么x2输出为0吗?我猜是因为浮点数表示方式对X1进行了舍入,是否有方法可以保留精度。
long double x1, x2;
x1= 0.087912088; // Note: 360/4095 = 0.087912088
x2 = 360/4095;
printf("%Lf, %Lf \n",x1, x2);
结果:
x1 =0.087912
x2= 0.000000
x2 = 360 / 4095.0; /* one of the operands now has a decimal point */
你将会得到什么
0.087912, 0.087912
作为输出结果。x2
更改为。x2 = 360.0 / 4095.0;
或者x2 = 360.0 / 4095;
并且会得到与上面相同的结果。
正如@chris所提到的,仅使用一个.
也足够了。
关于精度,针对你之前的问题:
你已经在使用长双精度浮点数了……我认为在不使用特殊库的情况下内部不能改变任何东西,但你可以显示更多位数。例如,
printf("%Lf, %.20Lf \n",x1, x2);
将产生
0.087912, 0.08791208791208791895
最后,正如@edA-qa mort-ora-y提醒我们的那样,您也可以将值强制转换为特定类型,但是它很重要,何时这样做。以下是一个简单的例子(请注意,由于v
是float
,因此无论如何赋值之后,值最终都会成为float
):
float v = 0;
/* values shown are BEFORE assignment */
v = (5 / 2); /* value is 2 due to integer truncation before assignment */
v = (float) (5 / 2); /* 2.0 as integer division occurs 1st, then cast to float */
v = (float) 5 / 2; /* 2.5 since 5 becomes 5.0 through casting first. */
float(a)
,double(4)
。 - edA-qa mort-ora-yx2 = 360/4096;
// int/int = int
因此,我预期结果为0。
如果内置类型的运算符不同,则会提升其中一个以使它们具有相同的类型(并且结果也是该类型)。所以你想要的是:
x2 = 1.0 * 360/4095; // or 360.0/4095
// This is
double * int / int
==> (double * double)/int
==> (double * double)/double
std::setprecision
。 - chris