Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this code returning different values? ( C# and VB.NET )

Tags:

c#

vb.net

VB.NET Code:

Module Module1

Sub Main()
    Dim x, y As Single
    x = 0 + (512 / 2 - 407) / 256 * 192 * -1
    y = 0 + (512 / 2 - 474) / 256 * 192
    Console.WriteLine(x.ToString + ": " + y.ToString)
    Console.ReadLine()
End Sub

End Module

Returns: 113,25: -163,5

C# Code:

class Program
{
    static void Main(string[] args)
    {
        float x, y;
        x = 0 + (512 / 2 - 407) / 256 * 192 * -1;
        y = 0 + (512 / 2 - 474) / 256 * 192;
        Console.WriteLine(x + ": " + y);
        Console.ReadLine();
    }
}

returns 0: 0

I don't get it, would appreciate an explanation.

like image 359
tryingit Avatar asked Dec 02 '10 03:12

tryingit


2 Answers

C# / performs integer division, truncating the fractional portion. VB.NET implicitly casts to Double.

To perform floating point division, cast to a floating point type:

    static void Main(string[] args)
    {
        float x, y;
        x = 0 + (512 / 2 - 407) / (float)256 * 192 * -1;
        y = 0 + (512 / 2 - 474) / (float)256 * 192;
        Console.WriteLine(x + ": " + y);
        Console.ReadLine();
    }
like image 107
Phil Hunt Avatar answered Nov 16 '22 22:11

Phil Hunt


C# literals like 0 and 512 are of type int. Any int/int (int divided by int) results in integer division, which discards any fractional remainder, losing precision. If you use float literals like 0F instead of 0 and 512F instead of 512, then C# will perform floating point division, which will retain the fractional part.

static void Main(string[] args)
{
    float x, y;
    x = 0F + (512F / 2F - 407F) / 256F * 192F * -1F;
    y = 0F + (512F / 2F - 474F) / 256F * 192F;
    Console.WriteLine(x + ": " + y);
    Console.ReadLine();
}
like image 9
Mike Clark Avatar answered Nov 16 '22 20:11

Mike Clark