Why does Decimal.Divide(int, int) work, but not (int / int)?

后端 未结 8 854
旧时难觅i
旧时难觅i 2020-12-08 03:18

How come dividing two 32 bit int numbers as ( int / int ) returns to me 0, but if I use Decimal.Divide() I get the correct answer? I\'m by no means

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 04:01

    You want to cast the numbers:

    double c = (double)a/(double)b;

    Note: If any of the arguments in C# is a double, a double divide is used which results in a double. So, the following would work too:

    double c = (double)a/b;

    here is a Small Program :

    static void Main(string[] args)
            {
                int a=0, b = 0, c = 0;
                int n = Convert.ToInt16(Console.ReadLine());
                string[] arr_temp = Console.ReadLine().Split(' ');
                int[] arr = Array.ConvertAll(arr_temp, Int32.Parse);
                foreach (int i in arr)
                {
                    if (i > 0) a++;
                    else if (i < 0) b++;
                    else c++;
                }
                Console.WriteLine("{0}", (double)a / n);
                Console.WriteLine("{0}", (double)b / n);
                Console.WriteLine("{0}", (double)c / n);
                Console.ReadKey();
            }
    

提交回复
热议问题