3

I was trying to run a program but it shows an error as:

Invalid binary operator float to int

When I tried making it float it says:

Invalid binary operator float to float

The problem is with % operator And its operands.

Please tell me what to do?

#include <stdio.h>
int main()
{
    float x,y;
    scanf("%f%f",&x,&y);
    float z=x%5.0f;
    if(x<=y && z==0)
        printf("%.2f",y-x-0.50);
    else if (x>y || z!=0)
            printf("%.2f",y);
    return 0;
 }
Pang
  • 9,564
  • 146
  • 81
  • 122

5 Answers5

4

Modulus % only makes sense with integers because it is defined as the remainder from integer division. You can't do integer division with floats.

chicks
  • 2,393
  • 3
  • 24
  • 40
4

Modulus operator doesn't work with float. You probably want to use the fmod function:

http://www.cplusplus.com/reference/cmath/fmod/

jgibbs
  • 430
  • 5
  • 13
2

Please note that % operator doesn't work with float. Instead you need to use fmod() for your requirement.

double fmod(double numerator, double denominator);
TryinHard
  • 4,078
  • 3
  • 28
  • 54
1

FMOD function is what you need:

#include <stdio.h>

int main(void){
    float x,y;
    double z;


    scanf("%f%f",&x,&y);

    z = fmod(x, 5.0f);

    if(x<=y && z==0)
        printf("%.2f",y-x-0.50);
    else if (x>y || z!=0)
            printf("%.2f",y);
    return 0;
 }
Michi
  • 5,175
  • 7
  • 33
  • 58
1

As @amdixon commented: "modulus operator % only applies between integers."

The operands of the % operator shall have integer type.
C11dr §6.5.5 2

In keeping with float arithmetic, suggest using fmodf() instead of % or fmod().
fmodf() computes the floating-point remainder of x/y.

// float z=x%5.0f;
float z = fmodf(x , 5.0f);

Notes:

The result of fmod() and family can be expected to be exact. Ref

The % is the remainder. Calling it the modulus operator overloads its meaning that often does not meet expectations when with a%b, either a or b is negative. See What's the difference between “mod” and “remainder”?

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256