1

I do not understand why a and b do not have the same result. Here is the corresponding code:

    public static void Main()
{
    double a = 10;
    double b = 10;

    for (int i=0; i<10; i++)
    {
        Console.WriteLine("a: " + a);
        Console.WriteLine("b: " + b + "\n");

        a = a * 1.1;
        b = b * (1+(1/10));
    }
}

//Ouput

a: 10 b: 10

a: 11 b: 10

a: 12.1 b: 10

a: 13.31 b: 10

a: 14.641 b: 10

a: 16.1051 b: 10

a: 17.71561 b: 10 ....

I hope you can help me.

Jachuc
  • 27
  • 8
  • 6
    1 is an integer. 10 is an integer. By the rules of C#, the result of the division of those is also an integer. You do the math. – Timbo Apr 25 '20 at 12:19
  • What Timbo said. In addition, *even if* you use floating point numbers, it is possible that the results *still* differ, see: https://stackoverflow.com/q/21895756/87698 – Heinzi Apr 25 '20 at 12:21

1 Answers1

0

As already stated by Timbo above. It is all about how the compiler treats the numbers 1 and 10. To demonstrate how it can be made to calculate the same, I have casted each of the numbers.

    public static void Main()
{
    double a = 10;
    double b = 10;

    for (int i=0; i<10; i++)
    {
        Console.WriteLine("a: " + a);
        Console.WriteLine("b: " + b + "\n");

        a = a * 1.1;
        b = b * ((double)1+((double)1/(double)10));
    }
}

Now both a and b are the same. I've created a .NET fiddle for the above example. https://dotnetfiddle.net/dUZdAi

keviny
  • 49
  • 4
  • 1
    Thanks guys - I didn't know this. Also found this thread because of your input: https://stackoverflow.com/questions/10851273/ – Jachuc Apr 25 '20 at 12:33
  • Nice link, also covers the characters that C# uses to specify as a literal. – keviny Apr 25 '20 at 17:02
  • I've updated the .NET fiddle to include c which uses the letter d appended to the numbers to instruct the compiler to treat the literal numbers as double. C is then printed the same. The code for that is a bit shorter, so nice to know. – keviny Apr 25 '20 at 17:07