Search code examples
c#arrayscastingintsigned

Signed int array typecast C#


When I run the following code:

public int[] finalResult = new int[dimension];
public float[] calculatedValue = new float[dimension];
.....
.....
finalResult[i] = (int) Math.Floor(calculatedValue[i]);
Console.WriteLine( "calculated:" + calculatedValue[i] 
    +  " final:" + finalResult[i] 
    + "  test: " +(int) Math.Floor(calculatedValue[i]));

The output is:

calculated:-0.02043936 final:0 test:-1

Why is "final" different from "test" when they are generated from exactly the same code? Which one is wrong, and why?

even simpler, and smaller fragment

finalResult[i]=(int)Math.Floor(-3.0002);
Console.WriteLine( "final: "+ finalResult[i]+ " test:" +(int)Math.Floor(-3.0002));

output final:0 test:-4

The remaining of the code is irrevelant as below proves I tried the following lastly,

public int[] junkArray = new int[dimension];
junkArray[i]=(int)Math.Floor(-3.0002);  //Junk Array is only assigned here in whole code
Console.WriteLine( "final: "+ (int) junkArray[i]+ " test:" +(int)Math.Floor(-3.0002));

I get output as final:0 test:-4


Solution

  • If I test the code

    var final = new int[1];
    var calc = new[] { -0.02043936f };
    final[0] = (int)Math.Floor(calc[0]);
    
    Console.WriteLine(
        "calc:{0} final:{1} test:{2}",
        calc[0],
        final[0],
        (int)Math.Floor(calc[0]));
    

    unsuprisingly I get the output

    calc:-0.02043936 final:-1 test:-1

    So, something else is wrong with your code.