0

I'm working on pset1 Greedy and am trying to use a modulo to eliminate the need for loops. The user inputs a float in the form of the "change" needed. This is converted into a whole number for easier math; then, the number of coins "ncoins" is calculated in integers.

change = round(change*100);

ncoins = change / 25;
change = change % 25;
ncoins = ncoins + (change / 10);
change = change % 10;
ncoins = ncoins + (change / 5);
change = change % 5;
ncoins = ncoins + (change / 1);

When I try to compile I get an error for each time modulo is used, saying:

invalid operands to binary expression ('float' and 'float')

I thought that after using round(), all numbers would be treated as integers. Is this incorrect? I have tried typecasting (int) nearly everywhere possible, but still the same error message. Am I simply incorrect in my thinking that my variables will become properly updated at the end of each line? I'm pretty much at a loss here.

Just in case, I have prototyped

float change;
int ncoins = 0;
  • You will understand what happens if run "man round" command in terminal. Without quotes, off course. – Vladimir Klimenko Mar 6 '15 at 20:03
3

If you tried typecasting to int, still the error would have existed because you are still storing the value in a float. So its basically like,

  • original value = 12.27
  • round()'s output = 1227.00
  • Typecasted result = 1227
  • Storing the typecasted value back in a float variable = 1227.00

And modulo operations don't work with floating point numbers. So, its better to use an integer variable in the last point, or simply doing something like

float change = GetFloat();
int Change = round(100*change);

And continue the rest of the calculations on Change(not change).

Good Luck.

| improve this answer | |
3

Modulo Operator ( % ) requires both the operands to be of type int .

In your code change is a floating point variable. Use an integer variable to store the rounded value.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .