Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid operands of types int and double to binary 'operator%'

Tags:

c++

After compiling the program I am getting below error

invalid operands of types int and double to binary 'operator%' at line 
"newnum1 = two % (double)10.0;"

Why is it so?

#include<iostream>
#include<math>
using namespace std;
int main()
{
    int num;
    double two = 1;
    double newnum, newnum1;
    newnum = newnum1 = 0;
    for(num = 1; num <= 50; num++)
    {

        two = two * 2;
    }
    newnum1 = two % (double)10.0;
    newnum = newnum + newnum1;
    cout << two << "\n";
    return 0;
}
like image 956
Rasmi Ranjan Nayak Avatar asked Feb 14 '12 14:02

Rasmi Ranjan Nayak


3 Answers

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

like image 93
Luchian Grigore Avatar answered Oct 31 '22 10:10

Luchian Grigore


Because % only works with integer types. Perhaps you want to use fmod().

like image 38
Oliver Charlesworth Avatar answered Oct 31 '22 09:10

Oliver Charlesworth


Yes. % operator is not defined for double type. Same is true for bitwise operators like "&,^,|,~,<<,>>" as well.

like image 35
Amar Avatar answered Oct 31 '22 10:10

Amar