开发者

C# double, decimal problems

Why does this calcuation: d开发者_如何转开发ouble number = (13 /(13+12+13))

equals 0?

It should be around 0.34, I think!

Thanks!


Because you are dividing an int with an int. You should be doing

double number = (13.0 /(13.0+12.0+13.0));


That are integers. So it does integer division. And thus truncates to the next lower(closer to 0) integer.

Add a .0 to a number like 13.0 to make it a double.


Because you're using all INT in your formula - it will be treated as INT for the result too.

Try this instead:

var result = 13.0 / (13.0 + 12.0 + 13.0)

and your result will be:

0.34210526315789475


Try adding a .0:

(13.0 /(13+12+13))

Otherwise you're dealing with integers.


Another option is to cast one of the arguments explicitly to double and thus forcing the runtime to perform double division. e.g. :

double result = ((double)13 / (13 + 12 + 13)); 


Adding a ".0" will help:

double number = (13.0 /(13.0+12.0+13.0));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜