im dumb
im dumb

Reputation: 151

C++ overloading addition not working correctly

So basically I'm trying to overload the plus operator so that it adds up change in price1 (1, 99) and price2 (2, 99). So 1.99 + 2.99 should equal 4.98 dollars. The code compiles, but I almost have the answer. Instead of 4.98, it gives out 3.1.98, which is not right. How can I fix this? I'm open to any suggestions or ideas

Here's my header file, titled MyClass.h:

#pragma once

class MyClass
{
public:
    int bills;
    double coins;

    MyClass (int, int);
    double sum () { return (bills + (coins * 0.01)); }
    MyClass operator+ (MyClass);
    MyClass(void);
    ~MyClass(void);
};

and my source file:

#include <iostream>     
#include <string>         
#include "MyClass.h"

using namespace std;

MyClass::MyClass(void)
{
}

MyClass::~MyClass(void)
{
}

MyClass::MyClass(int d, int c) 
{
  bills = d;
  coins = c;
}

MyClass MyClass::operator+ (MyClass param) {
  MyClass temp;
  temp.bills = bills + param.bills;
  temp.coins = (coins + param.coins) * 0.01; //Here is the problem, I think
  return temp;
}

void main() 
{
    MyClass price1 (1, 99);
    MyClass price2 (2, 99);
    MyClass total;
    total = price1 + price2;
    cout << total.bills << "." << total.coins << endl;
}

Upvotes: 0

Views: 97

Answers (3)

micheal.yxd
micheal.yxd

Reputation: 128

you should update

temp.bills = bills + param.bills;
temp.coins = (coins + param.coins) * 0.01;

TO

temp.bills = bills + param.bills + (coins + param.coins) / 100
temp.coins = (coins + param.coins) % 100

by the way, coins should be int type

Upvotes: 0

James Zhu
James Zhu

Reputation: 140

Curious as to why you're using a double for pennies. You don't usually have fractions of a pennies except when paying for gasoline, so int would make more sense.

A few things of note:

As aforementioned, be sure to do only temp.coins = coins + param.coins;. You're not transferring the value of the pennies, just the number of pennies.

Also, carry over pennies! 199 cents is 1 dollar 99 cents. This should translate into something like

int totalCoins = coins + param.coins;
temp.bills = bills + param.bills + totalCoins / 100;
temp.coins = totalCoins % 100;

assuming that you've turned coins into an int.

And by the way, you're not dumb. Every master was once a beginner.

Upvotes: 1

billz
billz

Reputation: 45440

You have converted coins in sum () already.

update

temp.coins = (coins + param.coins) * 0.01;

to

temp.coins = coins + param.coins;

And output statement is wrong, you print . by yourself

cout << total.sum() << endl;

Upvotes: 1

Related Questions