簡體   English   中英

C# - 舍入整數除法

[英]C# - Rounding the division of integers

Windows,C#,VS2010。

我的應用有這個代碼:

int[,] myArray=new int[10,2];
int result=0;
int x=0;
x++;

如下所示,如果結果在10.0001和10.9999之間; 結果= 10

result= (myArray[x,0]+myArray[x+1,0])/(x+1); 

我需要這個:如果結果> = 10 &&結果<10.5輪到10.如果結果> = 10.500 && <= 10.999輪到11。

請嘗試以下代碼。 但沒有奏效。

result= Math.Round((myArray[x,0]+myArray[x-1,0])/(x+1));

錯誤:以下方法或屬性之間的調用不明確:'System.Math.Round(double)'和'System.Math.Round(decimal)'

錯誤:無法將類型'double'隱式轉換為'int'。 存在顯式轉換(您是否錯過了演員?)

result= Convert.ToInt32(Math.Round((myArray[x,0]+myArray[x-1,0])/(x+1)));

錯誤:以下方法或屬性之間的調用不明確:'System.Math.Round(double)'和'System.Math.Round(decimal)'

在此先感謝,ocaccy pontes。

嘗試

result= (int)Math.Round((double)(myArray[x,0]+myArray[x-1,0])/(x+1));

這應該解決你的編譯器錯誤。

第一個(“錯誤:以下方法或屬性之間的調用不明確:'System.Math.Round(double)'和'System.Math.Round(decimal)'”)通過將被除數轉換為double來解決“涓滴”使得除法的輸出也是 double以避免精度損失。

您還可以將函數參數顯式轉換為double以獲得相同的效果:

Math.Round((double)((myArray[x,0]+myArray[x-1,0])/(x+1)));

(注意括號的位置)。

第二個錯誤(“錯誤:無法將類型'double'隱式轉換為'int'。存在顯式轉換(您是否缺少轉換?)”)通過顯式將Math.Round的返回值轉換為intMath.Round

我知道這是一個3歲的問題,但這個答案似乎運作良好。 也許有人會發現這些擴展方法的價值。

// Invalid for Dividend greater than 1073741823.
public static int FastDivideAndRoundBy(this int Dividend, int Divisor) {
    int PreQuotient = Dividend * 2 / Divisor;
    return (PreQuotient + (PreQuotient < 0 ? -1 : 1)) / 2;
}

// Probably slower since conversion from int to long and then back again.
public static int DivideAndRoundBy(this int Dividend, int Divisor) {
    long PreQuotient = (long)Dividend * 2 / Divisor;
    return (int)((PreQuotient + (PreQuotient < 0 ? -1 : 1)) / 2);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM