Division returns zero

2018-12-31 09:29发布

I am having this simple calculation returning zero can't figure it out

decimal share=(18 / 58)*100;

标签: c#
6条回答
零度萤火
2楼-- · 2018-12-31 09:49

You are working with integers here. Try using decimals for all the numbers in your calculation.

decimal share = (18m / 58m) * 100m;
查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 09:51

18 / 58 is an integer division, which results in 0.

If you want decimal division, you need to use decimal literals:

decimal share = (18m / 58m) * 100m;
查看更多
ら面具成の殇う
4楼-- · 2018-12-31 09:51

decimal share = (18 * 100)/58;

查看更多
君临天下
5楼-- · 2018-12-31 09:57

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.

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 18m as one of the variables to be calculated.

// 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() );
查看更多
情到深处是孤独
6楼-- · 2018-12-31 09:58

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}");
查看更多
倾城一夜雪
7楼-- · 2018-12-31 10:08

Because the numbers are integers and you perform integer division.

18 / 58 is 0 in integer division.

查看更多
登录 后发表回答