C语言 什么错误:二进制 % 的无效操作数(有 'float' 和 'int')是什么意思

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25914458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:23:40  来源:igfitidea点击:

What does error: invalid operands to binary % (have ‘float’ and ‘int’) mean

c

提问by Dumb

#include <stdio.h>

int main(void) 
{
    float with;
    float inacbal;
    float acleft;
    scanf("%f",&with);
    scanf("%f",&inacbal);
    if((with%5)==0)//error here
    {
        acleft=inacbal-with-0.50;
        printf("%f",acleft);
    }
    else
        printf("%f",inacbal);
    return 0;
}

回答by legends2k

float with;
if((with%5) == 0)

is incorrect. You can apply %only to integers. If you really want to do a modulo operation on float, then use fmodor if you're not bothered about the sign of the remainder, then use the new IEEE 754r mandated C99's remainder. From Sun's Numerical Computation Guide:

是不正确的。您只能应用于%整数。如果您真的想对 进行模运算float,则使用fmod或者如果您不关心余数的符号,则使用新的 IEEE 754r 强制要求的 C99 的余数。来自 Sun 的数值计算指南

The remainder(x,y) is the operation specified in IEEE Standard 754-1985. The difference between remainder(x,y) and fmod(x,y) is that the sign of the result returned by remainder(x,y) might not agree with the sign of either x or y, whereas fmod(x,y) always returns a result whose sign agrees with x.

余数(x,y) 是IEEE 标准754-1985 中规定的操作。余数(x,y)和fmod(x,y)之间的区别是余数(x,y)返回的结果的符号可能与x或y的符号不一致,而fmod(x,y)总是返回符号与 x 一致的结果。

回答by Spikatrix

You are getting that error because you can't use the modulus operator (%) with float.

您收到该错误是因为您不能将模运算符 ( %) 与float.

If you want to calculate the remainder of it,use fmod()like this:

如果你想计算它的余数,fmod()像这样使用:

fmod(with,5);

fmodwill return the remainder of the division. Don't forget to include math.hin order to use fmod.

fmod将返回除法的剩余部分。不要忘记包含math.h以使用fmod.