C program for finding remainder from floating point division using fmod

Post Free Ads for Agri, Solar, Eco products

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