Why in modulus division on floats or doubles cannot be performed in C programming? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why in modulus division on floats or doubles cannot be performed in C programming?

Example: float x=22.313, y=17.27; printf("%f", x%y ); //error

30th Jun 2021, 5:04 AM
Aswin Kumar S
Aswin Kumar S - avatar
7 Answers
+ 4
you can use fmod() function from <math.h> to compute modulo of irrational numbers: https://en.cppreference.com/w/c/numeric/math/fmod
30th Jun 2021, 5:36 AM
visph
visph - avatar
+ 3
in C/C++ both operands must be whole numbers ^^
30th Jun 2021, 5:10 AM
visph
visph - avatar
+ 2
because modulo operator only works on whole numbers: performs whole division (return rest)
30th Jun 2021, 5:08 AM
visph
visph - avatar
+ 2
Why it cant find the remainder for the division of two irrational numbers? Why the author designed modulo that won't work for this situation? I'm asking for the reason.
30th Jun 2021, 5:13 AM
Aswin Kumar S
Aswin Kumar S - avatar
+ 2
because there's no remainder when using irrational division... however you could compute what you expect by doing: int i = x/y; float r = x - i*y; at least for y as whole number...
30th Jun 2021, 5:20 AM
visph
visph - avatar
0
Here's a manual build: float flmod(float a, float b) { return a - (int) (a / b) * b; } # Hope this helps
1st Jul 2021, 12:18 PM
Calvin Thomas
Calvin Thomas - avatar