不能做除法 [英] Can't do division

查看:141
本文介绍了不能做除法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int h1 = 2;
int d1 = 4;
decimal c1 = d1/(d1+h1);
Console.WriteLine("{0:F9}", c1);



控制台显示0,00000000000,但我期望看到0,6666666并在年底,也许7。有什么问题?我尝试了不同的方法,但总能看到0,00000000 ...

Console shows 0,00000000000, but I expected to see 0,6666666 and maybe 7 in the end. What's the problem? I tried different methods, but always see 0,00000000...

推荐答案

这是因为你做的整数除法。你需要投一个值,以做一个小数除法为十进制:

It's because you're doing an integer division. You need to cast one value to decimal in order to do a decimal division :

int h1 = 2;
int d1 = 4;
decimal c1 = (decimal)d1 / (d1 + h1);



基本上,你可以翻译当前存在问题的行为:

Basically, you can translate the current problematic behavior as:

decimal c1 = (decimal)(d1 / (d1 + h1));
decimal c1 = (decimal)(4 / (2 + 4));
decimal c1 = (decimal)(4 / 6);
decimal c1 = (decimal)(0); <-- Integer division
decimal c1 = 0m;

这就是为什么你需要或者分子或分母是明确一个小数了。

That's why you need either the numerator or denominator to be explicitly a decimal already.

此外,在这里你的铸造是完全不相干的,你只需要触发小数除法。这4条线具有完全相同的结果:

Also, where you do the casting it is totally irrelevant, you just need to trigger the decimal division. Those 4 lines have exactly the same result :

decimal c1 = (decimal)d1 / (d1 + h1);
decimal c2 = d1 / ((decimal)d1 + h1);
decimal c3 = d1 / (d1 + (decimal)h1);
decimal c4 = d1 / (decimal)(d1 + h1);

这篇关于不能做除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆