简体   繁体   中英

C# - Rounding the division of integers

Windows, C#, VS2010.

My app has this code:

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

Like below, if the result is between 10.0001 and 10.9999; result=10

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

I need this: if the result>=10&&result<10.5 rounds to 10. if the result between >=10.500&&<=10.999 rounds to 11.

Try the codes below. But not worked.

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

Error: The call is ambiguous between the following methods or properties: 'System.Math.Round(double)' and 'System.Math.Round(decimal)'

Error: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)

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

Error: The call is ambiguous between the following methods or properties: 'System.Math.Round(double)' and 'System.Math.Round(decimal)'

Thanks in advance, ocaccy pontes.

Try

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

That should iron out your compiler errors.

The first one ("Error: The call is ambiguous between the following methods or properties: 'System.Math.Round(double)' and 'System.Math.Round(decimal)'") is resolved by converting the dividend to a double , which 'trickles down' such that the output of the division is also a double to avoid loss of precision.

You could also explicitly convert the function argument to a double for the same effect:

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

(Note the placement of the parentheses).

The second error ("Error: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)") is fixed by explicitly converting the return value of Math.Round to an int .

I know this is a 3 year old question, but this answer seems to work well. Maybe someone will find these extension methods of value.

// 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM