How can I divide two integers to get a double?

2018-12-31 19:16发布

How do I divide two integers to get a double?

标签: c# math
5条回答
情到深处是孤独
2楼-- · 2018-12-31 19:34

You want to cast the numbers:

double num3 = (double)num1/(double)num2;

Note: If any of the arguments in C# is a double, a double divide is used which results in a double. So, the following would work too:

double num3 = (double)num1/num2;

For more information see:

Dot Net Perls

查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 19:42

Convert one of them to a double first. This form works in many languages:

 real_result = (int_numerator + 0.0) / int_denominator
查看更多
笑指拈花
4楼-- · 2018-12-31 19:57

cast the integers to doubles.

查看更多
一个人的天荒地老
5楼-- · 2018-12-31 19:58
var firstNumber=5000,
secondeNumber=37;

var decimalResult = decimal.Divide(firstNumber,secondeNumber);

Console.WriteLine(decimalResult );
查看更多
刘海飞了
6楼-- · 2018-12-31 19:59

Complementing the @NoahD's answer

To have a greater precision you can cast to decimal:

(decimal)100/863
//0.1158748551564310544611819235

Or:

Decimal.Divide(100, 863)
//0.1158748551564310544611819235

Double are represented allocating 64 bits while decimal uses 128

(double)100/863
//0.11587485515643106

In depth explanation of "precision"

For more details about the floating point representation in binary and its precision take a look at this article from Jon Skeet where he talks about floats and doubles and this one where he talks about decimals.

查看更多
登录 后发表回答