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

2019-01-22 16:42发布

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 a c# guy.

标签: c# math int divide
8条回答
Animai°情兽
2楼-- · 2019-01-22 17:17

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();
        }
查看更多
对你真心纯属浪费
3楼-- · 2019-01-22 17:20

int is an integer type; dividing two ints performs an integer division, i.e. the fractional part is truncated since it can't be stored in the result type (also int!). Decimal, by contrast, has got a fractional part. By invoking Decimal.Divide, your int arguments get implicitly converted to Decimals.

You can enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.:

int a = 42;
int b = 23;
double result = (double)a / b;
查看更多
登录 后发表回答