0

I decided to try learning to code again for the upteenth time and I'm currently trying to refresh my memory by creating a banking program where a user can withdraw and deposit money. I'm trying to create a function that checks if a user input is a number that goes beyond the cent value and then prompts them to re-enter if so. Unfortunately, when I run the program it will always tell me that there is an invalid entry.

#include <iostream>
#include <cmath>

using namespace std;

// The following is the function spoken of.
double yagoof(double c) {
    double cent = .01;
    double rem = fmod(c, cent);
    cout << rem << endl;

    while (rem != 0) {
        cout << "Invalid entry. Please enter a number rounded to the nearest cent.\n\n";
        cin >> c;
        rem = fmod(c, cent);
        cout << rem << endl;
    }
    return c;
}

int main(){
...
}

I added the "cout << rem..."s after getting frustrated and wanting to see if I can figure something out. It will always tell me that rem is '.01'.

I guess I'm curious as to what I did wrong here. I've reviewed it in my head a few times and I'm not getting anywhere.

I can post the whole code if needed, I just didn't do it now because it has a bunch of notes.

pppery
  • 3,731
  • 22
  • 33
  • 46
Ryamix
  • 1
  • 2
  • You're getting caught by rounding errors. The value of 0.01 has no exact representation as a double so this method is inherently flawed. The right way to do is would be to read the input as a string. Count the number of significant digits after the decimal point and reinput if it is > 2. Only when you are happy with the input should you convert the string to a double. – john Jul 06 '20 at 17:28
  • 2
    You should never use floats for monetary values. Use decimal (int) number of cents instead. If you use cin, cin into a string and parse it as int.int – Jeffrey Jul 06 '20 at 17:28
  • Yes, what @Jeffrey said, let me amend my comment above to 'when you are happy with the input, remove the decimal point and convert to an integer that represents the number of cents'. Money is an integral quantity best represented as an integer, not a continuously varying quantity (like temperature say) which is best represented as a double. – john Jul 06 '20 at 17:30
  • *I'm curious as to what I did wrong here.* -- Nothing, except assuming that all decimal floating point numbers can be accurately represented on a binary computing machine. – PaulMcKenzie Jul 06 '20 at 17:38

0 Answers0