+ 1
Cout<<5.0*2 works fine, but cout<< 5.0%2 gives an error. Why?
11 Answers
+ 1
https://code.sololearn.com/chH4syqZv6dB/?ref=App
Trate, pero no se si te sirva.
+ 4
Yes the modulo of float number will give errors.If you try to perform % operation on two float, compiler will show error as - invalid operands to binary % (have âfloatâ and âfloatâ). Hence, use fmod(), pass the two values/variables as parameters and dont forget to include the header file <math.h> or <cmath> while using fmod() in your program.
float x=5.55,y=3.33,rem2;Â
rem2=fmod(x,y);Â
cout<<"Remainder = "<<rem2<<" (using fmod)"<<endl;Â
+ 3
The modulo(%) is coresponding to the rest of a division were the quotient, divider and the dividing are all integers number, we cannot talk of modulo, when we talk of a decimal part in a number, otherwise, it's have no interest
+ 3
Nathan Sikati
Got it,
Wonderfully explained.
+ 2
Aayu when we make a division, we have a/b= c+d
a is the dividing
b is the divider
c is the quotient
d is the rest
For example, we have
7/3=2+1
we want a,b,c and d all to be integers
The modulo is the rest of the division, so d is the modulo here.
The purpose of the modulo is to have a quotient(c), that's an integer.
If a is a float, we cannot calculate the rest because any way, the rest will not be an integer.
For example 7.1/3=2+1.1, but, thé rest cannot be integer, so C++ will not calculate the modulo because it most be an integer.
To fix that issue, a general rule in C++ is that the modulo function cannot be applied on a float, or a non integer.
Are you okay??
+ 2
Modulo function is for int not float or double
+ 1
" division were the quotient... can't talk of modulo"
Nathan Sikati
I don't understand?
0
This confusionizationized me
0
He's to smart for me lol
0
WHAT???????
0
Modulo opertor gives reminder & the remainder is an integer. So it is necessary that both the operands are integer.
Take an example, 5.3%3
here you see that 5.3 = 53/10 (float division) i. e 53 is already divided by a number and there is no remainder, 53/10 = 5 +(53%10)/10 = 5.3 so there is only quotient but no remainder, and when you use a operator with integer and float, the float gets higher precedence & the result converted into float, so for that reason 5.3 % 3 is invalid because there is no remainder for floating points.
& thats why 5.0 % 2 is invalid, but this will work fine. cout<<(int)5.0%2; because you are doing integer division here.
Summary : For integer division there are two parts, quotient and remainder. For floating division there is only quotient.