C# 如何将两个整数相除以获得双精度值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/661028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I divide two integers to get a double?
提问by leora
How do I divide two integers to get a double?
如何将两个整数相除以获得双精度值?
采纳答案by NoahD
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:
注意:如果 C# 中的任何参数是 a double
,double
则使用除法导致 a double
。因此,以下内容也将起作用:
double num3 = (double)num1/num2;
For more information see:
有关更多信息,请参阅:
回答by Mark Ransom
Convert one of them to a double first. This form works in many languages:
首先将其中一个转换为双精度。此表格适用于多种语言:
real_result = (int_numerator + 0.0) / int_denominator
回答by Stephen Wrighton
cast the integers to doubles.
将整数转换为双精度。
回答by fabriciorissetto
Complementing the @NoahD's answer
补充@NoahD的回答
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 表示分配 64 位,而十进制使用 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 articlefrom Jon Skeet where he talks about floats
and doubles
and this onewhere he talks about decimals
.
有关二进制浮点表示,精度更多的细节来看看这篇文章从乔恩斯基特,他谈到floats
与doubles
和这一个地方他谈到decimals
。
回答by Rejwanul Reja
var firstNumber=5000,
secondeNumber=37;
var decimalResult = decimal.Divide(firstNumber,secondeNumber);
Console.WriteLine(decimalResult );