Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 433
Ocaccy Pontes Avatar asked Mar 24 '23 03:03

Ocaccy Pontes


1 Answers

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.

like image 70
Fabian Tamp Avatar answered Mar 29 '23 18:03

Fabian Tamp