【问题标题】:C language: float % float why expression must have integral type [duplicate]C语言:float%float为什么表达式必须具有整数类型[重复]
【发布时间】:2018-02-08 02:06:03
【问题描述】:

我尝试做这个操作,看看这个操作是只占用完整部分(20%4)还是全部(20.4%4.4)

float x = 20.4;
float y = 4.0;
float z;
z = x%y;

得到了这个编译器error:

表达式必须是整型

【问题讨论】:

  • 查看如何使用 fmod。

标签: c


【解决方案1】:

您只能使用% 获取整数除法的余数。

要获得浮点除法的余数,请改用fmod() 函数。

【讨论】:

    【解决方案2】:

    您可以使用modff 来解决问题。

    float res = modff(x,&y)
    

    整数部分存储在y 中,小数部分返回。 % 不能与非整数类型一起使用。

    【讨论】:

      【解决方案3】:

      不能模浮点数。解决这个问题的方法。

      float x = 20.4
      int xint = (int)(x);
      int y = 4;
      float z = x % y + (x-xint)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-28
        • 2011-09-26
        相关资源
        最近更新 更多