I am working on pset1 greedy problem. I am getting wrong output. I have written just logical part here.


   count+=x/q;    //q= quarter

same for dime, nickel and penny. and at the end I am printing count. is there any mistake ???

Thank you in advance.. :)


2 things to be pointed out :

  1. That's GetFloat() AFAIK
  2. x should be updated as x = x%q and not sum of x and x%q because x%q will return directly the amount that coins of value q fail to achieve, and hence smaller valued coins come in demand.
  • now I am getting error "invalid operands to binary expression('float' and 'float') x=x%q". Is this mod operator I am using is wrong ?? – sweets Apr 15 '15 at 5:04
  • what is the variable type for q? int? float? other? – Cliff B Apr 15 '15 at 8:08
  • It is Integrr...@CliffB – sweets Apr 15 '15 at 9:39
  • you get that error because x is of type float, use an integer instead of x, i.e. int y = 100*x; and then replace x with y in rest of your snippet – sinister Apr 15 '15 at 10:52
  • Yeah...it worked...thank you...@sinister... but, it is necessary to use round() in this program... without round(), I am getting correct result... – sweets Apr 16 '15 at 5:40

I wanted to give a complete answer for this question for future reference. There are a few concepts here that may be causing you issues and I want to make sure future readers understand how to implement this code.

When dealing with floats (As you do in this problem) its a good idea to assume only a certain level of precision, however you CAN assume this level of precision.

What you do in the above example is to simply multiply a float by 100 (Which is syntactically correct) but you never cast it to an int meaning its still just as imprecise. You should use an explicit cast and also ensure your fixing any inherent issues with the round() function.

Additionally you have some unneeded code in your problem where you are only executing if x >= q, well this is fine its not needed as the logic will still work otherwise. if x is too small to be divided it will just return 0 from the division and its value for the Modulus. If you where doing more then these actions it might be worth the check but in the current situation its not really needed.

You must log in to answer this question.

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