There is a Money class:

class Money { private: unsigned long rouble; unsigned char penny;}; 

There is a constructor:

 Money::Money(const double money) { double intpart; double frac = modf(money, &intpart); if (intpart < 0) { ok = false; } while (frac > 100) { frac--; intpart += 1; } penny = static_cast<unsigned long>(deleteDot(frac)); rouble = static_cast<unsigned long>(intpart); } 

When transferring it is valid 1.2232, it gives out 1,184. I went through the debugger, but I still did not understand why this is happening.

deleteDot method:

 double Money::deleteDot(double &frac) { int x, value = 10; std::stringstream ss; std::string ncbc; //numeral_count_before_comma rouble = (int)frac; ss << frac - (int)frac; //1.12-1=0.12 ncbc = ss.str(); size_t pos = ncbc.find('.'); if (pos != ncbc.npos) { x = ncbc.size() - 1 - pos; } for (int i = 1; i < x; i++) { value *= 10; } frac -= (int)frac; frac *= value; return frac; } 

    1 answer 1

    This is just no mystery.

    For 1.2232, your deleteDot function returns 2232, which is the number that is converted to the ungigned char (although you write unsigned long )

     penny = static_cast<unsigned long>(deleteDot(frac)); 

    trimmed to 184.

    How to write deleteDot , you did not ask :)

    But hint - take the fractional part, do not try to work with string representation. Multiply by 100 and round up to the whole as you need.

    • And how to write deleteDot correctly?) - ANurbaev
    • And I hinted ... - Harry
    • one
      In my opinion, you did not hint, but fully told ... - AR Hovsepyan
    • @ARHovsepyan Well ... I did not write the finished code :) - Harry