C#:如何对整数进行四舍五入的简单数学运算?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/299094/
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-03 22:12:48  来源:igfitidea点击:

C#: How do I do simple math, with rounding, on integers?

c#mathrounding

提问by Ian Boyd

i want the result of an equation rounded to the nearest integer. e.g.

我想要一个方程的结果四舍五入到最接近的整数。例如

137 * (3/4) = 103

Consider the following incorrect code.

考虑以下不正确的代码。

int width1 = 4;
int height1 = 3;

int width2 = 137;
int height2 = width2 * (height1 / width1);

What is the proper way to perform "integer" math in C#?

在 C# 中执行“整数”数学的正确方法是什么?

Do i really have to do:

我真的必须这样做吗:

int height2 = (int)Math.Round(
      (float)width2 * ((float)height1 / (float)width1)
   );

采纳答案by Aaron

As said above, you should do the multiplication before the division. Anyway you could write your expression with casting only the divisor:

如上所述,您应该在除法之前进行乘法。无论如何,您可以只使用除数来编写表达式:

int height2 = (int)Math.Round(width2 * (height1 / (float)width1));

回答by Jeffrey L Whitledge

int height2 = (width2 * height1) / width1;

回答by James Curran

The elaborate on Jeffery's message, since you generally a better chance of truncated needed decimals than you have of overflowing a 32-bit integer (and because multiplication & division is commutative), you should generally do multiplication before division.

Jeffery 消息的详细说明,因为与溢出 32 位整数相比,通常截断所需小数的机会更好(并且因为乘法和除法是可交换的),所以您通常应该在除法之前进行乘法。

回答by plinth

Do multiplication first (as long as they're not likely to overflow) and division second.

首先进行乘法(只要它们不太可能溢出)然后进行除法。

3/4 == 0 in integer math (integer math doesn't round on division, it truncates).

整数数学中的 3/4 == 0(整数数学不舍入除法,而是截断)。

If you really need rounding, you have to either work in fixed point, floating point, or play around with the modulus.

如果您确实需要舍入,则必须以定点、浮点或模数进行操作。

回答by dongilmore

int height2 = ((width2 * height1 * 10) + 5) / (width1 * 10);

Prior to any integer division, check to make certain the divisor is not zero. Also note this assumes positive quotient. If negative, roundoff needs to be -5, not +5.

在进行任何整数除法之前,请检查以确保除数不为零。另请注意,这假定为正商。如果为负,则舍入需要为 -5,而不是 +5。

回答by andrewrk

I will fix the incorrect code by adding zero lines of code:

我将通过添加零行代码来修复不正确的代码:

float width1 = 4;
float height1 = 3;

float width2 = 137;
float height2 = width2 * (height1 / width1);

You should use floats for variables that can possibly contain decimals. This includes heights calculated from ratios. You can always cast to int later if that is a problem.

对于可能包含小数的变量,您应该使用浮点数。这包括根据比率计算的高度。如果这是一个问题,您可以稍后再转换为 int。

回答by rwallace

Never cast to float, it has even less precision than a 32-bit integer. If you're going to use floating point, always use double instead of float.

永远不要转换为浮点数,它的精度甚至低于 32 位整数。如果要使用浮点数,请始终使用 double 而不是 float。

回答by Ruben

I think this is the most elegant way to do this:

我认为这是最优雅的方法:

Math.round(myinteger * 0.75);

Using 0.75 instead of 3/4 will implicitly cast it to an double/float and why not use the default functions that are provided for this?

使用 0.75 而不是 3/4 会将其隐式转换为双精度/浮点数,为什么不使用为此提供的默认函数?

回答by Tod

Convert's conversions always round so:

Convert 的转换总是四舍五入:

int height2 = Convert.ToInt32(width2 * height1 / (double)width1);

回答by Pianoman

Just stumbled upon this question. Aaron's answer seems almost right to me. But I'm very sure you need to specify midpointrounding if your problem is a "real world" problem. So my answer, based on Aaron's code, is

刚刚偶然发现了这个问题。亚伦的回答对我来说几乎是正确的。但是我很确定如果您的问题是“现实世界”问题,您需要指定中点舍入。所以我的答案,基于 Aaron 的代码,是

int height2 = (int)Math.Round(width2 * (height1 / (float)width1),MidpointRounding.AwayFromZero);

To see the difference run that code in console

要查看差异,请在控制台中运行该代码

    Console.WriteLine((int)Math.Round(0.5));
    Console.WriteLine((int)Math.Round(1.5));
    Console.WriteLine((int)Math.Round(2.5));
    Console.WriteLine((int)Math.Round(3.5));
    Console.WriteLine((int)Math.Round(0.5, MidpointRounding.AwayFromZero));
    Console.WriteLine((int)Math.Round(1.5, MidpointRounding.AwayFromZero));
    Console.WriteLine((int)Math.Round(2.5, MidpointRounding.AwayFromZero));
    Console.WriteLine((int)Math.Round(3.5, MidpointRounding.AwayFromZero));
    Console.ReadLine();

For details you may look at thisarticle.

有关详细信息,您可以查看这篇文章。