Home » Programming Languages » C Programs » How to solve : error: invalid operands to binary % (have ‘float’ and ‘double’)

How to solve : error: invalid operands to binary % (have ‘float’ and ‘double’)

If you are trying to run modulo / remainder operator like below, there are higher chances you might get an error as “error: invalid operands to binary” The solution for this error is as mentioned below.

 $ vim using_mod.c 
#include <stdio.h>

int main(void) {
        float num = 11.00;
        int remainder = num % 3.0;

        if (remainder == 0) {
                printf("number is divisible\n");
        } else {
                printf("number is not divisible: Remainder = %d\n", remainder);
        }
        return 0;
}
 $ gcc using_mod.c 
using_mod.c: In function ‘main’:
using_mod.c:5:22: error: invalid operands to binary % (have ‘float’ and ‘double’)
  int remainder = num % 3.0; 

Solution :

The remainder operator (otherwise known as the modulo operator) % is a binary operator (i.e., takes exactly 2 operands) and operates only on integer types (e.g., short, int, long, long long, etc).

Hence, we either need to change float to int, or typecast both the values before and after % operator. like

int remainder = (int)num % (int)3.0;

The complete working program will look like as below,

 $ vim using_mod.c 
#include <stdio.h>

int main(void) {
        float num = 6.00;
        int remainder = (int)num % (int)3.0;

        if (remainder == 0) {
                printf("number is divisible\n");
        } else {
                printf("number is not divisible: Remainder = %d\n", remainder);
        }
        return 0;
}

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment