Pregunta

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;
¿Fue útil?

Solución

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.

Otros consejos

You should assign your cast to a variable otherwise it's not doing anything. static_cast<int>(maxTotal) will return a value of type int

double maxTotal, minTotal;

cin >> maxTotal >> minTotal;

int addCalc;

int i_maxTotal = static_cast<int>(maxTotal);

if(i_maxTotal % 2 == 1)
        addCalc = minTotal;
else
        addCalc = 0;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top