Invalid operands of type 'double' and 'int' to binary 'operator%'

user2649644 picture user2649644 · Aug 4, 2013 · Viewed 10k times · Source

I'm writing a program for my control structures class and I'm trying to compile it. The only error, at least the only error the compiler is picking up is saying invalid operands of types 'double' and 'int' to binary 'operator%'. Most of the program isn't included since it's too long and doesn't really pertain to this problem, at least I don't believe.

double maxTotal, minTotal;

cin >> maxTotal >> minTotal;

int addCalc;

static_cast<int>(maxTotal);

if(maxTotal % 2 == 1)
     addCalc = minTotal;
else
     addCalc = 0;

Answer

Borgleader picture Borgleader · Aug 4, 2013

Your static_cast isn't doing anything. What you should be doing is:

if(static_cast<int>(maxTotal) % 2 == 1)

Variables in C++ cannot change types. Static cast returns the casted value it does not change the input variable's type, so you have to use it directly or assign it.

int iMaxTotal = static_cast<int>(maxTotal);

if(iMaxTotal % 2 == 1)
    addCalc = minTotal;
else
    addCalc = 0;

This would work too.