C# is rounding down divisions by itself

丶灬走出姿态 提交于 2019-11-26 13:49:38

i = 200 / 3 is performing integer division.

Try either:

i = (double)200 / 3

or

i = 200.0 / 3

or

i = 200d / 3

Declaring one of the constants as a double will cause the double division operator to be used.

200/3 is integer division, resulting in an integer.

try 200.0/3.0

You can specify format string with the desired number of decimal ponits:

double i;
i = 200 / 3.0;
Messagebox.Show(i.ToString("F6"));

200 / 3 this is an integer division. Change to: 200.0 / 3 to make it a floating point division.

Though the answer is actually 66.666, what is happening is that 200 / 3 is being calculated resulting in an integer. The integer is then being placed in the float. The math itself is happening as integer math. To make it a float, use 200.0 / 3. The .0 will cause it to treat 200 as a float, resulting in floating point math.

sclarson

Aside from the double vs int happening in that action, you're thinking of double as a precise unit. Try using the decimal datatype when you really care about accuracy.

More information at this answer: decimal vs double! - Which one should I use and when?

double i = 200.0 / 3;

double i = ((double)200)/3;

What happens is the two integers perform an integer divide, and then the integer answer is assigned to the float. To avoid that, always cast one of the numbers as a double.

Try this

i = 200d/3d;

and it will not round.

200 and 3 are both integers, so the result will be an integer. Convert one of them to a decimal.

All given answers are wrong because they translate the integer division into one of kind double, which is cleanly not what was asked for (at least from a performance standpoint). The obvious answer is elementary school math, multiply by 10, add 5 and divide again, all integer.

i = (2000 / 3 + 5 ) / 10

You are catching a second division here, which is better than doing double conversions but still far from perfect. You could go even further and multiply by another factor and add other values than five, thus allowing you to use right shifting instead of dividing by 10. The exact formula for doing this is left as an exercise to the reader. (Just google "divisions with Multiply Shift")

Have a nice day.

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