本文介绍了为什么浮点数和整数之间的乘法在C#中与C ++和FORTRAN 77不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在努力将FORTRAN 77中的一些代码转换为C#。我遇到了一个问题,即相同的外观表达式返回的结果与其他语言不同。例如: 下面的C#代码显示整数640437496 float f = .29822734f; int i =(int)(f * 2147480832); Console.WriteLine(i); 下面的C ++代码显示整数640437504 float f = .29822734; int i =(int)(f * 2147480832); std :: cout<< "i =" << i; 最后,这个FORTRAN 77代码与C ++共享结果: 640437504 整数i 实数f f = .29822734 i = int(f * 2147480832)写(*,*)i 感谢您的帮助。解决方案 尝试调查:在C#中,转到Build菜单,Configuration Manager,然后添加新的"x86"和"x64"平台。检查每种情况下的结果。 似乎在"x86"平台中你可以使用设置精度 _ controlfp_s 功能。它在C ++中可用,但您可以尝试在C#中调用它: [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); { 浮动 f = .29822734f; int i =( int )(f * 2147480832); Console.WriteLine(i); } _ controlfp_s( out cc,_PC_64,_MCW_PC); { 浮动 f = .29822734f; int i =( int )(f * 2147480832); Console.WriteLine(i); } 在"x86"平台的情况下检查这些结果。 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 640437496float f = .29822734f;int i = (int)(f * 2147480832);Console.WriteLine(i);The C++ code below displays the integer 640437504float f = .29822734;int i = (int)(f * 2147480832);std::cout << "i = " << i;Finally, this FORTRAN 77 code shares the result with C++: 640437504integer ireal ff = .29822734i = int(f * 2147480832)write ( *, * ) iI 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. 解决方案 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 )]staticexternint _controlfp_s(outuint currentControl,uint newControl,uint mask ); constuint _MCW_PC = 0x00030000;constuint _PC_24 = 0x00020000;constuint _PC_53 = 0x00010000;constuint _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. 这篇关于为什么浮点数和整数之间的乘法在C#中与C ++和FORTRAN 77不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 11-01 20:18