C# 为什么 Decimal.Divide(int, int) 有效,而不是 (int / int)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1043164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:50:45  来源:igfitidea点击:

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

c#mathintdivide

提问by

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.

为什么将两个 32 位 int 数字除以 ( int / int ) 返回给我0,但如果我使用,Decimal.Divide()我会得到正确答案?我绝不是 ac# 人。

采纳答案by Konrad Rudolph

intis an integer type; dividing two ints performs an integerdivision, 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 intarguments get implicitly converted to Decimals.

int是整数类型;除以两个整数执行整数除法,即小数部分被截断,因为它不能存储在结果类型中(也是int!)。Decimal,相比之下,有一个小数部分。通过调用Decimal.Divide,您的int参数将隐式转换为Decimals。

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

您可以int通过将至少一个参数显式转换为浮点类型来强制对参数进行非整数除法,例如:

int a = 42;
int b = 23;
double result = (double)a / b;

回答by Brian

If you are looking for 0 < a < 1 answer, int / int will not suffice. int / int does integer division. Try casting one of the int's to a double inside the operation.

如果您正在寻找 0 < a < 1 的答案, int / int 是不够的。int / int 做整数除法。尝试在操作中将 int 之一转换为 double。

回答by Gishu

I reckon Decimal.Divide(decimal, decimal)implicitly converts its 2 int arguments to decimals before returning a decimal value (precise) where as 4/5 is treated as integer division and returns 0

我认为Decimal.Divide(decimal, decimal)在返回十进制值(精确)之前将其 2 个 int 参数隐式转换为小数,其中 4/5 被视为整数除法并返回 0

回答by Andrew Rollings

In the first case, you're doing integer division, so the result is truncated (the decimal part is chopped off) and an integer is returned.

在第一种情况下,您正在执行整数除法,因此结果被截断(小数部分被截去)并返回一个整数。

In the second case, the ints are converted to decimals first, and the result is a decimal. Hence they are not truncated and you get the correct result.

在第二种情况下,首先将整数转换为小数,结果为小数。因此,它们不会被截断,您会得到正确的结果。

回答by Fredrik M?rk

The following line:

以下行:

int a = 1, b = 2;
object result = a / b;

...will be performed using integer arithmetic. Decimal.Divideon the other hand takes two parameters of the type Decimal, so the division will be performed on decimal values rather than integer values. That is equivalent of this:

...将使用整数算法执行。Decimal.Divide另一方面,需要两个类型的参数Decimal,因此除法将在十进制值而不是整数值上执行。这相当于:

int a = 1, b = 2;
object result = (Decimal)a / (Decimal)b;

To examine this, you can add the following code lines after each of the above examples:

要检查这一点,您可以在上述每个示例之后添加以下代码行:

Console.WriteLine(result.ToString());
Console.WriteLine(result.GetType().ToString());

The output in the first case will be

第一种情况的输出将是

0
System.Int32

..and in the second case:

..在第二种情况下:

0,5
System.Decimal

回答by Jaydeep Shil

You want to cast the numbers:

你想投射数字:

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

双 c = (双)a/(双)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:

注意:如果 C# 中的任何参数是双精度数,则使用双除法导致双精度数。因此,以下内容也将起作用:

double c = (double)a/b;

双 c = (双)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();
        }

回答by Dojo

The answer marked as such is very nearly there, but I think it is worth adding that there is a difference between using double and decimal.

标记为这样的答案非常接近,但我认为值得补充的是,使用 double 和 decimal 之间存在差异。

I would not do a better job explaining the concepts than Wikipedia, so I will just provide the pointers:

我不会比维基百科更好地解释这些概念,所以我只会提供一些指示:

floating-point arithmetic

浮点运算

decimal data type

十进制数据类型

In financial systems, it is often a requirement that we can guarantee a certain number of (base-10) decimal places accuracy. This is generally impossible if the input/source data is in base-10 but we perform the arithmetic in base-2 (because the number of decimal places required for the decimal expansion of a number depends on the base; one third takes infinitely many decimal places to express in base-10 as 0.333333..., but it takes only one decimal in base-3: 0.1).

在金融系统中,通常要求我们可以保证一定数量的(以 10 为底的)小数位精度。如果输入/源数据以 10 为基数,这通常是不可能的,但我们以 2 为基数执行算术(因为数字的十进制扩展所需的小数位数取决于基数;三分之一需要无限多个小数以 10 进制表示的位置为 0.333333...,但在 base-3 中只需要一位小数:0.1)。

Floating-point numbers are faster to work with (in terms of CPU time; programming-wise they are equally simple) and preferred whenever you want to minimize rounding error (as in scientific applications).

浮点数的处理速度更快(就 CPU 时间而言;编程方面它们同样简单)并且在您想要最小化舍入误差时首选(如在科学应用程序中)。

回答by Alp Altunel

In my case nothing worked above.

就我而言,上面没有任何效果。

what I want to do is divide 278 by 575 and multiply by 100 to find percentage.

我想要做的是将 278 除以 575 再乘以 100 来求百分比。

double p = (double)((PeopleCount * 1.0 / AllPeopleCount * 1.0) * 100.0);

%: 48,3478260869565 --> 278 / 575 ---> 0 %: 51,6521739130435 --> 297 / 575 ---> 0

%: 48,3478260869565 --> 278 / 575 ---> 0 %: 51,6521739130435 --> 297 / 575 ---> 0

if I multiply the PeopleCount by 1.0 it makes it decimal and division will be 48.34... also multiply by 100.0 not 100.

如果我将 PeopleCount 乘以 1.0,它会变成十进制,除法将是 48.34……也乘以 100.0 而不是 100。