World of warcraft Currency System C++

252 Views Asked by At

I am creating a currency system that is based in 3 types of coins (Gold, Silver and Copper) it works as 100 copper coins converts into 1 silver coin, and, 100 silver coin converts into 1 gold coin.

I made an struct like this

struct Money
{
    Money();
    Money(int copper, int silver, int gold);
    Money(Money& m);

    Money operator + (Money const& obj);
    Money operator - (Money const& obj);

    void operator += (Money const& obj);
    void operator -= (Money const& obj);

    void Balance();

    void Print();
    int c, s, g;
};

But the problem comes with the method Balance(). This method does the math to convert all the copper to silver and silver to gold.

I made this but I'm looking for a better solution if somebody can find it. I think that the performance of my method is poor.

void Money::Balance()
{
    if (c > 99) { s += c / 100; c = c % 100; }
    if (s > 99) { g += s / 100; s = s % 100; }

    if (c < 0 && s >= 0 && g > 0) { 
        (c += ((c / 101) + 1) * 100); 
        s -= (c / -101) + 1; 
    }
    if (s < 0 && g > 0) { 
        (s += ((s / 101) +1) * 100); 
        g -= (c / -101) + 1; 
    }
}

EDIT: The last 2 if-blocks are for negative money to convert for example (50g 10s -1c) in (50g 9s 99c) and just have negative in the first currency type. To not have (50g -9s -2c)

EDIT: I checked that there is a bug that if you have g > 0, s = 0 and c < 0 it wont take a silver so it will show negative copper.

Thank you for your answers <3

I tried to convert 100 copper to 1 silver and 100 silver to 100 gold. I think that my solution works but the performance is poor.

1

There are 1 best solutions below

3
hNq On

Remove the last part of your code and it works fine:

void Money::Balance()
{
  // Convert excess copper coins to silver coins
  s += c / 100;
  c %= 100;

 // Convert excess silver coins to gold coins
  g += s / 100;
  s %= 100;
}