gpt4 book ai didi

c# - 理解给定的计算(cast + multiplication)

转载 作者:可可西里 更新时间:2023-11-01 07:44:16 27 4
gpt4 key购买 nike

(int)((float)10.9 * 10)

的计算结果为 108。为什么?

IMO (int)-cast 应该在乘法运算后求值。

最佳答案

有趣的是,这里的问题是表达式是在编译时计算的,显然使用预期的单精度数学。这在调试和发布版本中都会发生:

    // this replaces the whole operation
IL_0001: ldc.i4.s 108
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: call void [mscorlib]System.Console::WriteLine(int32)

虽然案例 var f =((float)10.9 * 10);int i = (int)f; 仍然针对乘法进行了优化,但使用 double 。因为转换是在单独的步骤中完成的,所以我猜它会使编译器感到困惑(??):

    IL_000b: ldc.r4 109      // 109 result for the first part
IL_0010: stloc.1
IL_0011: ldloc.1
IL_0012: conv.i4 // separate conversion to int
IL_0013: stloc.2
// rest is printing it
IL_0014: ldloc.1
IL_0015: box [mscorlib]System.Single
IL_001a: ldstr " "
IL_001f: ldloc.2
IL_0020: box [mscorlib]System.Int32
IL_0025: call string [mscorlib]System.String::Concat(object, object, object)
IL_002a: call void [mscorlib]System.Console::WriteLine(string)

老实说,在第二种情况下,编译器生成了错误的代码,这可能就是为什么 C++ 像瘟疫一样避免优化浮点代码。幸运的是,这只是这种测试代码的问题,完全可以在编译时完成,实际的变量乘法就可以了。

其实我也试过这个:

Console.WriteLine((int)(float.Parse(Console.ReadLine()) * int.Parse(Console.ReadLine())));

并给它 10.9 和 10,结果如预期的那样是 108。

关于c# - 理解给定的计算(cast + multiplication),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33515080/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com