Modulus of two float or double numbers in C language

C language | Modulus of two float or double numbers: Here, we will learn how can we find the modulus/remainder of non-integer values in C language?
Submitted by IncludeHelp, on June 26, 2020

As we know that modules also known as the remainder of the two numbers can be found using the modulus (%) operator which is an arithmetic operator in C/C++. The modules operator works with integer values i.e. modulus operator is used to find the remainder of two integer numbers. If the numbers are float or double the the modulus operators doesn't work.

Consider the below example,

#include <stdio.h>

int main()
{
    float x = 10.23f;
    float y = 3.1f;

    float result = x % y;

    printf("result = %f\n", result);

    return 0;
}

Output:

main.c: In function ‘main’:
main.c:8:22: error: invalid operands to binary % (have ‘float’ and ‘float’)
     float result = x % y;
                      ^

See the output – it says that invalid operands to modulus operator.

Then, how to find the remainder/modulus of two float or double numbers?

There is a library function remainder(), declared in math.h. It can be used to find the modules of float, double, and integer (also) numbers.

The remainder() function accepts two parameters and returns the remainder.

Syntax:

remainder(x, y);

Here, x and y are the floating-point or integral values.

Example 1:

#include <stdio.h>
#include <math.h>

int main()
{
    float x = 10.23f;
    float y = 3.1f;

    float result = remainder(x, y);

    printf("result = %f\n", result);

    return 0;
}

Output:

result = 0.930000

Example 2:

#include <stdio.h>
#include <math.h>

int main()
{
    // integer numbers
    int a = 10;
    int b = 3;

    // float numbers
    float m = 10.23f;
    float n = 3.1f;

    // double numbers
    double x = 123456789.10;
    double y = 1233.1;

    printf("remainder(%d,%d) = %lf\n", a, b, remainder(a, b));
    printf("remainder(%f,%f) = %lf\n", m, n, remainder(m, n));
    printf("remainder(%lf,%lf) = %lf\n", x, y, remainder(x, y));

    return 0;
}

Output:

remainder(10,3) = 1.000000
remainder(10.230000,3.100000) = 0.930000
remainder(123456789.100000,1233.100000) = 50.200000



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.