Extremely basic division equation not working in c#

前端 未结 3 1644
我寻月下人不归
我寻月下人不归 2021-01-23 00:36

I can\'t get this to divide into a decimal. It is rounding to value 0.

    private void button24_Click(object sender, EventArgs e)
    {
        double x = 0;         


        
相关标签:
3条回答
  • 2021-01-23 00:50

    It's integer division and those are the expected outputs.

    double x = 1.0 / 5;  // this will not perform integer division
    double x = 1/5;  // this does  (1/5 = 0).  
    double x = 1D / 5; // this will not because 1 is treated as a double
    
    0 讨论(0)
  • 2021-01-23 00:51

    You can do one of the follow:

    double x = 1;
    double y = 1.5;
    
    double ans = x / y;
    
    0 讨论(0)
  • 2021-01-23 00:57

    Replace double x = 1/5 with double x = 1.0/5 and that should fix it. Because both numbers you're dividing are integers, it still processes it as an integer, rather than as a double. When you think through logically, it makes some sense - it does the division in whatever form those numbers are and then saves it to the variable; the variable type is inconsequential to the actual equation.

    (I realize there are other answers already, but hopefully this will help you see why the issue exists.)

    0 讨论(0)
提交回复
热议问题