none
Why is Multiplication Between a Float and a Integer Different in C# Than C++ and FORTRAN 77 RRS feed

  • Question

  • I am working on translating a bit of code from FORTRAN 77 to C#. I ran into the problem that an identical looking expression is returning different results than in other languages. For Example:

    The C# code below displays the integer 640437496

    float f = .29822734f;
    int i = (int)(f * 2147480832);
    Console.WriteLine(i);

    The C++ code below displays the integer 640437504

    float f = .29822734;
    int i = (int)(f * 2147480832);
    std::cout << "i = " << i;

    Finally, this FORTRAN 77 code shares the result with C++: 640437504

    integer i
    real f
    f = .29822734
    i = int(f * 2147480832)
    write ( *, * ) i

    I can't find any other people struggling with this? Did I miss a standard that is different from C++ and FORTRAN in C#? Did I do something wrong?

    Thanks for the help.


    • Edited by Mistcurve Wednesday, January 16, 2019 3:12 PM Edited to more clearly identify the problem expression
    Wednesday, January 16, 2019 3:04 PM

All replies

  • Try an investigation: in C#, go to Build menu, Configuration Manager, and add new “x86” and “x64” platforms. Check the results in each case.

    Seems that in “x86” platform you can set the precision using the _controlfp_s function. It is available in C++, but you can try calling it in C# to:

    [DllImport( "msvcrt", CallingConvention = CallingConvention.Cdecl )]

    static extern int _controlfp_s( out uint currentControl, uint newControl, uint mask );

     

    const uint _MCW_PC = 0x00030000;

    const uint _PC_24 = 0x00020000;

    const uint _PC_53 = 0x00010000;

    const uint _PC_64 = 0x00000000;

     

    . . .

    uint cc;

     

    _controlfp_s( out cc, _PC_24, _MCW_PC );

    {

        float f = .29822734f;

        int i = (int)( f * 2147480832 );

        Console.WriteLine( i );

    }

     

    _controlfp_s( out cc, _PC_64, _MCW_PC );

    {

        float f = .29822734f;

        int i = (int)( f * 2147480832 );

        Console.WriteLine( i );

    }

     

    Check these results in case of “x86” platform.

    Wednesday, January 16, 2019 7:20 PM
  • Thanks for the response, I will try doing this tomorrow. I may have found the solution though. It appears that C#'s multiplication will use double precision for the calculation, and then convert to a float afterwards for some reason. 
    Wednesday, January 16, 2019 10:26 PM