2010-12-02 15 views
10

Código VB.NET:¿Por qué este código devuelve valores diferentes? (C# y VB.NET)

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 

Devuelve: 113,25: -163,5

C# Código:

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(); 
    } 
} 

devuelve 0: 0

No lo entiendo, agradecería una explicación.

Respuesta

18

C# / realiza la división de enteros, truncando la porción fraccionaria. VB.NET lanza implícitamente a Double.

Para realizar la división de punto flotante, echado a un tipo de coma flotante:

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(); 
    } 
+2

Gracias por su ayuda. – tryingit

+1

¡Eres bienvenido! –

9

C# literales como 0 y 512 son de tipo int. Cualquier int/int (int dividido por int) da como resultado una división entera, que descarta cualquier resto fraccional, perdiendo precisión. Si utiliza literales float como 0F en lugar de 0 y 512F en lugar de 512, entonces C# realizará una división de coma flotante, que retendrá la parte fraccionaria.

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(); 
} 
+1

Gracias por su ayuda también. – tryingit

+0

tryingit, eres bienvenido. la mejor de las suertes. –

Cuestiones relacionadas