0

For some reason the value of divide() still prints as an int even though I declared it as a double.

#include <iomanip>
#include <iostream>
#include <cmath>

using namespace std;

class Calculator{
    private:
        int a = 0;
        int b = 0;

    public:
        Calculator(int n1, int n2) : a(n1), b(n2) {}

        Calculator() = default;

        int getN1() const{
            return a;
        }

        int getN2() const{
            return b;
        }
        
        int add() const{
            return a + b;
        }
    
        int subtract() const{
            return a - b;
        }
    
        int multiply() const{
            return a * b;
        }
        
        double divide() const{
            return a / b;
        }
  
    void showDetails() const{
        cout << " " << endl;
        cout << "Computed:" << endl;
        cout << "Sum = " << add() << endl;
        cout << "Difference = " << subtract() << endl;
        cout << "Product = " << multiply() << endl;
        cout << "Quotient = " << setprecision(2) << fixed << divide() << endl;
    }
};

int main() {
    int n1;
    int n2;

    cout << "Enter Num1: ";
        cin >> n1;
    cout << "Enter Num2: ";
        cin >> n2;

    Calculator x(n1, n2);
    x.showDetails();
  

    return 0;
}

It worked when I declared the initial values as double but I was tasked to assign the initial values as int.

Kaiki
  • 1
  • 1
  • 5
    `a / b;` is still `int`. The `double` doesn't take hold until the return value conversion is done, and by that time `a / b` is already over with. `return static_cast(a)/b;` will *probably* do what you want. – WhozCraig Dec 09 '22 at 21:41
  • `the value of divide() still prints as an int` What do you mean by this? – eerorika Dec 09 '22 at 21:44
  • 1
    Search this site for "integer division". It seems to surprise newcomers to C++ that diving two integers produces an integer. – Drew Dormann Dec 09 '22 at 21:51

1 Answers1

0

a and b are declare as integers. Make it double. int upon int gives int value hence change any one or both of them to double.

Barbrik
  • 3
  • 4