SimpleCalculator(for lab)
标签(空格分隔): 程序设计实验 c++
本人学院
Description:
Write a SimpleCalculator class that has public methods for adding, subtracting, multiplying and dividing two
doubles. SimpleCalculator has a private data member called answer. After performing
an operation, assign the result to answer. And a member function named getAnswer that will retrieve the result of
the last arithmetic operation performed by the object. Also, add a constructor for class SimpleCalculator
that initializes the value of answer to 0.
Note: You may expect the divisor of the divide function will not equal 0.
Test.cpp
// Lab Exercise 1: CalcTest.cpp
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include "SimpleCalculator.h"
int main() {
double a;
double b;
cin >> a >> b;
SimpleCalculator sc; // instantiate SimpleCalculator
cout << "The value of a is: " << a << "\n";
cout << "The value of b is: " << b << "\n\n";
sc.add(a, b);
cout << "Adding a and b yields " << sc.getAnswer() << "\n";
sc.subtract(a, b);
cout << "Subtracting b from a yields " << sc.getAnswer() << "\n";
sc.multiply(a, b);
cout << "Multiplying a by b yields " << sc.getAnswer() << "\n";
sc.divide(a, b);
cout << "Dividing a by b yields " << sc.getAnswer() << endl;
}
SimpleCalculator.h
// Lab Exercise 1: SimpleCalculator.h
// class SimpleCalculator definition
class SimpleCalculator {
public:
SimpleCalculator();
void add(double, double);
void subtract(double, double);
void multiply(double, double);
void divide(double, double);
double getAnswer() const;
private:
double answer;
}; // end class SimpleCalculator
读题
my answer
#include<iostream>
#include"SimpleCalculator.h"
using namespace std;
SimpleCalculator::SimpleCalculator() {
answer = 0;
}
void SimpleCalculator::add(double a, double b) {
answer = a + b;
}
void SimpleCalculator::subtract(double a, double b) {
answer = a - b;
}
void SimpleCalculator::multiply(double a, double b) {
answer = a * b;
}
void SimpleCalculator::divide(double a, double b) {
answer = a / b;
}
double SimpleCalculator::getAnswer() const {
return answer;
}
the standard answer
// Lab Exercise 1: SimpleCalculator.cpp
#include "SimpleCalculator.h"
// default constructor
SimpleCalculator::SimpleCalculator() {
answer = 0;
} // end class SimpleClassculator constructor
// function add definition
void SimpleCalculator::add(double a, double b) {
answer = a + b;
} // end function add
// function subtract definition
void SimpleCalculator::subtract(double a, double b) {
answer = a - b;
} // end function subtract
// function multiply definition
void SimpleCalculator::multiply(double a, double b) {
answer = a * b;
} // end function multiply
// function divide definition
void SimpleCalculator::divide(double a, double b) {
answer = a / b;
} // end function divide
// return answer
double SimpleCalculator::getAnswer() const {
return answer;
} // end function getAnswer