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;
}
Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply