【问题标题】:Why is an int promoted in multiplication but not division? [closed]为什么 int 在乘法中被提升而不是在除法中? [关闭]
【发布时间】:2015-05-12 01:41:19
【问题描述】:

我的理解是,例如,当一个浮点数和一个整数相乘时,int 被提升为一个浮点数,因此乘积可以有一个小数部分。另一方面,当将浮点数除以 int 时,没有提升,并且商的任何小数部分都将被丢弃。这种不对称的原因是什么?

float f1 = 13.3;
int i1 = 2;
float product = f1 * i1;  // Product will be 26.6
float quotient = f1 / i1;  // Quotient will be 6.0

编辑:好吧,我想我错了。 int 在除法中也被提升。正确的?截断仅适用于具有两个整数的除法。正确的?这里的网站最佳实践是什么,我应该删除这个问题,因为它太离谱了吗?

【问题讨论】:

  • 你为什么这么认为?
  • 你的理解有误。没有不对称性。
  • 商是 6.65。投票结束为“无法复制”

标签: c types casting


【解决方案1】:

如果你像这样运行这个程序:

#include <stdio.h>

int main()
{
    float f1 = 13.3;
    int i1 = 2;
    float product = f1 * i1;  // Product will be 26.6
    float quotient = f1 / i1;  // Quotient 

    printf( "product = %f\n",product );
    printf( "quotient = %f\n", quotient );
}

那么输出是

product = 26.600000
quotient = 6.650000

根据 C 标准(6.5.5 乘法运算符)

3 对操作数执行通常的算术转换。

和(6.3.1.8 常用算术转换)

否则,如果任一操作数对应的实数类型是浮点数, 另一个操作数在不改变类型域的情况下转换为 对应实类型为float的类型。62)

【讨论】:

    【解决方案2】:

    另一方面,当将浮点数除以整数时,没有提升,商的任何小数部分都将被丢弃。

    这根本不正确。保留小数部分。在这个意义上,乘法和除法运算的工作方式相同。

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 2012-04-20
      • 2018-04-04
      相关资源
      最近更新 更多