司和浮点 [英] Division and floating points
问题描述
有人能帮助我,为什么X2打印零。
我猜是因为浮点重新presentation X1四舍五入,有没有办法让precession。
长双X1,X2;
X1 = 0.087912088; //注:4095分之360= 0.087912088
X2 =四千○九十五分之三百六;
的printf(%LF,%LF \\ N,X1,X2);
结果:
X1 = 0.087912
X2 = 0.000000
问题是的整数截断的..在划分两个整数=>的结果将与扔掉小数部分另一个整数。 (因此,例如在情况下,当一个整数除法的实际结果是3.9,截断将使3(即它不圆))。
在你的情况下,如果将其更改为:
X2 = 360 / 4095.0; / *一个操作数现在有一个小数点* /
您将获得
0.087912,0.087912
作为输出
也就是说,只要的一个或除法运算符 /
的操作数的两个的是浮动/双打,结果将是太(也就是说,它会被提升为float /双)。所以,我可以改变了 X2
到
χ2= 360.0 / 4095.0;
或
χ2= 360.0 / 4095;
和会获得与上述相同的结果。
正如@克里斯提到的只是使用。
就足够了。
以上重约precision你的问题:
您已经与长双打的工作..我不认为在内部,除非你使用一些特殊的图书馆就可以改变什么,但你肯定可以显示更多的数字。例如,
的printf(%LF,%.20Lf \\ n,X1,X2);
将产生
0.087912,0.08791208791208791895
最后,@ EDA-QA MORT-ORA-Y提醒我们,你也可以的投的值,某些类型的,但重要的在的你做到这一点。一个简单的例子(注意,该值最终为浮动
的之后的在任何情况下的分配,因为 v
是浮动
)
浮动V = 0;
显示/ *值是分配前* /
V =(5/2); / *值为2,由于转让前截断的整数* /
V =(浮点)(5/2); / * 2.0的整数除法发生1日,然后转换为浮动* /
V =(浮点)5/2; / * 2.5自5变为5.0通过第一个铸造。 * /
Can Anyone help me why x2 prints zero. I guess because of floating point representation X1 is rounded off, is there way to keep the precession.
long double x1, x2;
x1= 0.087912088; // Note: 360/4095 = 0.087912088
x2 = 360/4095;
printf("%Lf, %Lf \n",x1, x2);
Result:
x1 =0.087912
x2= 0.000000
The problem is integer truncation .. you are dividing two integers => the result will be another integer with the fractional part thrown away. (So for instance in the case when the real result of an integer division would be 3.9, truncation would make it 3 (ie. it doesn't round)).
In your case, if you change this to:
x2 = 360 / 4095.0; /* one of the operands now has a decimal point */
you'll get
0.087912, 0.087912
as output.
I.e., as soon as one or both of the operands of the division operator /
are float/doubles, the result will be too (i.e., it will be "promoted" to float/double). So I could have changed x2
to
x2 = 360.0 / 4095.0;
or
x2 = 360.0 / 4095;
and would have gotten the same result as above.
As mentioned by @chris just using a .
is sufficient too.
Re your question above about precision:
You are already working with long doubles .. I don't think internally you can change anything unless you use some special library, but you can certainly display more digits. E.g.,
printf("%Lf, %.20Lf \n",x1, x2);
will yield
0.087912, 0.08791208791208791895
Finally, as @edA-qa mort-ora-y reminds us, you can also cast values to certain types, but it matters when you do it. A simple example (note that the values end up as float
after the assignment in any case since v
is a 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. */
这篇关于司和浮点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!