Search code examples
c#mscorlib

Multiplication without operators in C# MSCorLib?


I was digging through the MSCoreLib and I came across something interesting.

I am confused how this even works.

(ref http://referencesource.microsoft.com/#mscorlib/system/math.cs line 32)

   // This table is required for the Round function which can specify the number of digits to round to
      private static double[] roundPower10Double = new double[] { 
          1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8,
          1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15
      };          

      public const double E  = 2.7182818284590452354;

It appears they are creating a double array. Then, for each value multiplying 1 * E * nth. That's what APPEARS to be happening however they aren't using any operators?

What is this dark magic?


Solution

  • No, you're confused by the notation.

    2e4 == 2E4 == 20000
    

    simply means 2 * 10^4. e or E is the notation for "exponent". It is useful to prevent one from writing a lot of zeros. The second E has nothing to do with the first. The second is an identifier. But identifiers are not allowed in double literals (and literals in general).

    Example:

    say you wish to store the Avogadro constant, then you can write:

    double Avogadro = 602300000000000000000000.0;
    

    But it is confusing (since you need to count zeros and one can easily make a mistake). One can however write:

    double Avogadro = 6.023e23;