C program for finding remainder from floating point division using fmod

As we have seen in “C program for using modulo operator, finding if number is dividable and print remainder.” if we want to use modulo operator, we have to use either integer or typecast the value with “int” and result also was integer.

Now, what if we have to do float operations and want to identify whether certain float number is completely divisible by another number or not and if not what could be the remainder. For this we have to use math libraries function “fmod” and link the same library during the compilation.

 $ vim remainder_from_float_division.c 
#include <stdio.h>
#include <math.h>       /* fmod */

int main () {
        float i = fmod (15.0,3.0);
        printf("i is %f\n", i);

        if (i==0) {
                printf("number is divisible by 3\n");
        } else {
                printf("number is not divisible by 3\n");

        printf ( "fmod of 5.3 / 2 is %f\n", fmod (5.3,2) );
        printf ( "fmod of 18.5 / 4.2 is %f\n", fmod (18.5,4.2) );
        return 0;

Note: we are passing addtional “-lm” to link the math library during compilation.
If you don’t link the same, you may get an error like,

/tmp/ccUbRn5m.o: In function `main':
remainder_from_float_division.c:(.text+0x2c): undefined reference to `fmod'
 $ gcc -o remainder_from_float_division remainder_from_float_division.c -lm 
 $ ./remainder_from_float_division
i is 0.000000
number is divisible by 3
fmod of 5.3 / 2 is 1.300000
fmod of 18.5 / 4.2 is 1.700000
Android Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense Multimedia - Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question