user5724577
user5724577

Reputation:

Error: invalid operands of types 'float' and 'float' to binary 'operator%'

I just started to program in C and I found a problem when running the program. The error is the following,resto == a % b;

[Error] invalid operands of types 'float' and 'float' to binary 'operator%' in C

#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:

postimg.org/image/guoxt6evn

Upvotes: 1

Views: 66426

Answers (2)

Following comment discussion, the problem boils down to this line:

    float a, b, somma, differenza, prodotto, quoziente;
    int resto;

You need to change a and b to integers:

    float somma, differenza, prodotto, quoziente;
    int a, b, resto;

Due to the issue pointed out by @artm

Upvotes: 1

tdao
tdao

Reputation: 17668

The error is the following,' resto == a % b' ;

That's because the modulus operator % cannot apply to float or double. It's meant to get the remainder when integer type x is divided by y. It does not have any meaning when you use it with float or double.

Also spotted by Draco18s, this resto == a % b is not what you want even if a and b are integer type. The == is logical operator, so that expression will yield a temporary value of 1 (for true) and 0 otherwise. But that temporary value is NOT assigned to resto at all. You need to use assignment operator = instead.

Upvotes: 6

Related Questions