C语言 错误:'float' 和 'float' 类型的无效操作数转换为二进制 'operator%'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34500361/
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
Error: invalid operands of types 'float' and 'float' to binary 'operator%'
提问by Giorgio Ricca
I just started to program in C and I found a problem when running the program.
The error is the following,resto == a % b;
我刚开始用C编程,在运行程序时发现了一个问题。错误如下resto == a % b:
[Error] invalid operands of types 'float' and 'float' to binary 'operator%' in C
[错误] 在 C 中将“float”和“float”类型的无效操作数转换为二进制“operator%”
#include<stdio.h>
#include <math.h>
char n;
int main (){
printf ("Programma che svolge ogni tipo di operazione aritmetica tra 2 numeri a e b\n'n' per chiudere\nPremere 'invio' per continuare\n");
float a, b, somma, differenza, prodotto, quoziente;
int resto;
while (n=getchar()!='n'){
printf ("Inserisci a\n");
scanf ("%f",&a);
printf ("Inserisci b\n");
scanf ("%f",&b);
somma = a + b;
differenza = a - b;
prodotto = a * b;
quoziente = a / b;
resto = a % b;
printf ("somma = %f + %f = %f\n",a,b,somma);
printf ("differenza = %f - %f = %f\n",a,b,differenza);
printf ("prodotto = %f * %f = %f\n",a,b,prodotto);
printf ("quoziente = %f / %f = %f\n",a,b,quoziente);
printf ("resto = %f %% %f = %d\n",a,b,resto);
}
return 0;
}
The solution there:
那里的解决方案:
回答by artm
The error is the following,' resto == a % b' ;
错误如下,' resto == a % b' ;
That's because the modulus operator %cannot apply to floator double. It's meant to get the remainderwhen integer type xis divided by y. It does not have any meaning when you use it with floator double.
那是因为模运算符%不能应用于floator double。当整数类型被除以时,它的意思是得到余数。与或一起使用时,它没有任何意义。xyfloatdouble
Also spotted by Draco18s, this resto == a % bis not what you want even if aand bare integer type. The ==is logical operator, so that expression will yield a temporary value of 1(for true) and 0otherwise. But that temporary value is NOTassigned to restoat all. You need to use assignment operator =instead.
此外,通过Draco18s发现,这resto == a % b是不是你想要的,即使a和b是整数类型。的==是逻辑运算符,从而表达将产生的临时值1(对于真)和0其它。但是根本没有分配该临时值resto。您需要改用赋值运算符=。
回答by ori0n
devi usare la http://www.cplusplus.com/reference/cmath/fmod/fmodper fare il resto di tipi float o double
devi usare la http://www.cplusplus.com/reference/cmath/fmod/ fmodper fare il resto di tipi float o double
回答by Draco18s no longer trusts SE
Following comment discussion, the problem boils down to this line:
经过评论讨论,问题归结为这一行:
float a, b, somma, differenza, prodotto, quoziente;
int resto;
You need to change aand bto integers:
你需要改变a和b整数:
float somma, differenza, prodotto, quoziente;
int a, b, resto;
Due to the issue pointed out by @artm
由于@artm 指出的问题


