Division returns zero

前端 未结 6 1364
[愿得一人]
[愿得一人] 2020-11-22 04:19

This simple calculation is returning zero, I can\'t figure it out:

decimal share = (18 / 58) * 100;
相关标签:
6条回答
  • 2020-11-22 05:02

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

    decimal share = (18m / 58m) * 100m;
    
    0 讨论(0)
  • 2020-11-22 05:03

    Because the numbers are integers and you perform integer division.

    18 / 58 is 0 in integer division.

    0 讨论(0)
  • 2020-11-22 05:05

    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;
    
    0 讨论(0)
  • 2020-11-22 05:15

    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() );
    
    0 讨论(0)
  • 2020-11-22 05:18

    decimal share = (18 * 100)/58;

    0 讨论(0)
  • 2020-11-22 05:19

    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}");
    
    0 讨论(0)
提交回复
热议问题