Division returns zero

前端 未结 6 1508
[愿得一人]
[愿得一人] 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: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() );
    

提交回复
热议问题