C # error in Modulo Operator%

The solution to one mistake. I came to some interesting discoveries.

Result of this procedure

static void Main(string[] args) { int i4 = 4; Console.WriteLine("int i4 = 4;"); Console.WriteLine("i4 % 1 = {0}", i4 % 1); double d4 = 4.0; Console.WriteLine("double d4 = 4.0;"); Console.WriteLine("d4 % 1 = {0}", d4 % 1); Console.WriteLine("-----------------------------------------------------------"); int i64 = 64; double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0); Console.WriteLine("int i64 = 64;"); Console.WriteLine("double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0) = {0}", dCubeRootOf64); Console.WriteLine("dCubeRootOf64 = {0}", dCubeRootOf64); Console.WriteLine("dCubeRootOf64 % 1 = {0} ?????????????? Why 1. ??????????", dCubeRootOf64 % 1); Console.ReadLine(); } 

is an

 int i4 = 4; i4 % 1 = 0 double d4 = 4.0; d4 % 1 = 0 ----------------------------------------------------------- int i64 = 64; double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0) = 4 dCubeRootOf64 = 4 dCubeRootOf64 % 1 = 1 ?????????????? Why 1. ?????????? 

int 4 % 1 = 0 - correct

double 4.0 % 1 = 0 - correct

But the error is:

Math.Pow (64, 1.0 / 3.0)% 1 = 1

The cubic root of 64 is 4. Why in this case 4 % 1 = 1 ?

+7
source share
2 answers

Math.Pow(64, 1.0 / 3.0) returns 3.9999999999999996 .
When displayed, it is rounded to 4 .

Taking it modulo 1, return 0.99999999999999956 , which is similarly rounded to 1 when displayed.

You can see the true values โ€‹โ€‹by adding .ToString("R")

+12
source

dCubeRootOf64 % 1 = 1 returns 1 instead of 0; reason Math.Pow(i64, 1.0 / 3.0) returns 3.9999999999999996 and 3.9999999999999996 % 1 returns 0.99999999999999956 , which in turn is rounded to 1.

So the result is 1.

+3
source

All Articles