-2

I want to calculate change due, and convert it to pennies.

#include <iostream>
using namespace std;

int main()
{
    float cost   = 5.15,
          paid   = 10.00,
          change = 0.0;

    int pennies = 0.0;

    change = paid - cost;
    pennies = static_cast<int>(change * 100);

    cout << change << endl;       //4.85
    cout << pennies << endl;      //484  ??

    return 0;
}

Pennies evaluates to 484, where did my penny go?

I've tried this with float and double, with and without static_cast.

I'm in an intro c++ class so the point is to do this with basic operations.

Dose (4.85 * 100) evaluate to like 484.999999... when using floats so its being truncated?

RaSedg
  • 111
  • 1
  • 10

1 Answers1

1

Use round.........................................................

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
  • 1
    I'll take "answers that should be in the comment section" for 500 Alex – Cory Kramer Sep 23 '15 at 13:18
  • you are hilarious @CoryKramer – Lamour Sep 23 '15 at 13:19
  • @CoryKramer Is something of what I said wrong or inappropriate for an answer? The OP has a truncation problem which will be fixed by rounding instead of truncating. Oh, and you lost me with "500 Alex"... what does that refer to? – Peter - Reinstate Monica Sep 23 '15 at 13:26
  • @PeterSchneider There is a specific close reason that says something like "this is a link only answer" which is not useful to anyone. To be a complete, standalone answer, how about you add *how* to use `std::round` to fix their problem. The fact that you had to pad your "answer" out with filler characters should have tipped you off that you were too brief. The rest of my comment was a poor joke referencing the show "Jeopardy" – Cory Kramer Sep 23 '15 at 13:28
  • @CoryKramer Hm. I thought the word "round" with a link should spark the joy of insight? The usage seems trivial. -- 500 Alex: Oh :-). – Peter - Reinstate Monica Sep 23 '15 at 13:29
  • I wasn't so much asking for a solution as I was insight into the cause of the problem, Thank you for your "sincere" response. – RaSedg Sep 23 '15 at 14:20