C# 除法返回零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9288904/
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
Division returns zero
提问by Zo Has
This simple calculation is returning zero, I can't figure it out:
这个简单的计算返回零,我想不通:
decimal share = (18 / 58) * 100;
采纳答案by Daniel Lee
You are working with integers here. Try using decimals for all the numbers in your calculation.
您在这里使用整数。尝试对计算中的所有数字使用小数。
decimal share = (18m / 58m) * 100m;
回答by Petar Ivanov
18 / 58is an integer division, which results in 0.
18 / 58是整数除法,结果为 0。
If you want decimal division, you need to use decimal literals:
如果要十进制除法,则需要使用十进制文字:
decimal share = (18m / 58m) * 100m;
回答by Albin Sunnanbo
Because the numbers are integers and you perform integer division.
因为数字是整数并且您执行整数除法。
18 / 58is 0in integer division.
18 / 58是0整数除法。
回答by Prabhavith
decimal share = (18 * 100)/58;
十进制份额 = (18 * 100)/58;
回答by Kraang Prime
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
由于有些人几乎从计算结果为 0 的任何线程链接到此,因此我将其添加为解决方案,因为并非所有其他答案都适用于案例场景。
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18mas one of the variables to be calculated.
需要对各种类型进行计算以获得该类型作为结果的概念适用,但是上面仅显示“十进制”并使用它的缩写形式,例如18m要计算的变量之一。
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
回答by adonthy
Whenever I encounter such situations, I just upcast the numerator.
每当我遇到这种情况时,我只是向上推分子。
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");

