How can I get the result with decimal number in division? C++, Pi

佐手、 提交于 2019-12-01 14:37:51
pi = pi + (negativeController * 4 / denominator);

The (negativeController * 4 / denominator) expression results in an int because both negativeController and denominator are int. In other words, you're doing an integer division here which explains why you don't get the expected result.

Declare either (or both) of them as double to force a floating-point division.

You should change :-

int denominator; to

double denominator;

See here

I think changing negativeController and denominator to int would do the trick as the sub-expression is being evaluated on integers thus loosing precision.

pi = pi + (negativeController * 4 / denominator);

In this line, you have an integer division (because both operands of / are of type int), meaning that the fractional part of the division's result is discarded.

To use floating point division, at least one operand/side needs to be of type float or (long) double. The easiest way to achieve this would in this case be a change of 4 (a literal of type int) to 4.0 (a literal of type double):

Then, when calculating the result of *, negativeController will also be converted to double (usual arithmetic conversions), yielding a double as the left-hand side operand of / which in turn causes denominator (the rhs) to also be converted into a double and so on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!