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

c++
139,286

Solution 1

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.

Solution 2

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

Solution 3

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

Share:
139,286

Related videos on Youtube

Rasmi Ranjan Nayak
Author by

Rasmi Ranjan Nayak

Always ready for programming. Favorite Programming Languages C, C++, Python, Java, Android

Updated on June 06, 2020

Comments

  • Rasmi Ranjan Nayak
    Rasmi Ranjan Nayak almost 4 years

    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;
    }
    
    • Lundin
      Lundin about 12 years
      (double)10.0 this typecast does nothing. 10.0 is already double type. 10.0f is float type, and 10 is (signed) integer type.
    • Keith Thompson
      Keith Thompson over 8 years
      @Lundin: 10 is specifically of type int, not just of any arbitrary signed integer type.
  • Matt
    Matt about 10 years
    usage: include math.h and then use fmod(15, 2);. More in the fmod docs.