Addition and subtraction of complex numbers using class in C++ - c++

I have here a code that is supposed to ask the user two sets of real and imaginary numbers.
#include <iostream>
using namespace std;
class Complex {
public:
double r;
double i;
public:
Complex();
void add(Complex, Complex);
void subtract(Complex, Complex);
void print();
};
Complex::Complex() {
r = i = 0;
}
void Complex::add (Complex op1, Complex op2) {
r = op1.r+op2.r;
i = op1.i+op2.i;
}
void Complex::subtract (Complex op1, Complex op2) {
r = op1.r-op2.r;
i = op1.i-op2.i;
}
void Complex::print () {
cout << r << i;
}
int main () {
Complex operand1, operand2, result;
cout << "Input real part for operand one: " << endl;
cin >> operand1.r;
cout << "Input imaginary part for operand one: " << endl;
cin >> operand1.i;
cout << "Input real part for operand two: " << endl;
cin >> operand2.r;
cout << "Input imaginary part for operand two: " << endl;
cin >> operand2.i;
result.add(operand1, operand2);
cout << "The sum is " << result.add << endl;
result.subtract(operand1, operand2);
cout << "The difference is " << result.subtract << endl;
}
However, when I compiled the program, lots of errors are displayed (std::basic_ostream) which I don't even get.
Another issue I'm having is in the function void::Complex print. There should be a condition inside cout itself. No if-else. But I have no idea what to do.
The program must run like this:
Input real part for operand one: 5
Input imaginary part for operand one: 2 (the i for imaginary shouldn't be written)
Input real part for operand two: 8
Input imaginary part for operand two: 1 (again, i shouldn't be entered)
/then it will print the input(ed) numbers/
(5, 2i) //this time with an i
(8, 1i)
/then the answers/
The sum is 13+3i.
The difference is -3, 1i. //or -3, i
Please help me! I'm new in C++ and here in stackoverflow and your help would be very appreciated. Thank you very much!

The line
cout << "The sum is " << result.add << endl;
is incorrect, as add is a method so result.add will be a pointer to that method, and cout does not know how to handle it - which makes the compiler spit it out.
Change the line to
cout << "The sum is ";
result.print();
cout << endl;
You need to do the same for the line
cout << "The difference is " << result.subtract << endl;
As to coding style, the two methods are overwrting an existing complex number. Perhaps having a the function like this would be better
Complex &Complex::add (const Complex &op) {
r += op.r;
i += op.i;
return *this;
}
This will enable you to chain additions together and also just add a complex number to the existing complex number.
In addition you could make the class variables r and i private. This will require an alternative constructor:
Complex:Complex(double real, double imaginary) : r(real), i(imaginary) {};
Finally you may wish to consider operator overloading - I am sure you can google that to find a reasonable tutorial.

In main, after you call result.add, you put the same function in the cout stream when it doesn't return anything. I think you meant to write cout << "the sum is " << result.print();

You are already using the std:: namespace. Just use the complex number library in it like this answer suggests: Addition of complex numbers using classes

#include <iostream>
using namespace std;
class Complex {
public:
double r;
double i;
public:
void add(Complex, Complex);
void subtract(Complex, Complex);
void print();
};
void Complex::add (Complex op1, Complex op2) {
r = op1.r + op2.r;
i = op1.i + op2.i;
}
void Complex::subtract (Complex op1, Complex op2) {
r = op1.r - op2.r;
i = op1.i - op2.i;
}
void Complex::print () {
cout << "("<<r<<", " << i <<")";
}
int main () {
Complex operand1, operand2, result;
cout << "\nInput real part for operand one: " << endl;
cin >> operand1.r;
cout << "Input imaginary part for operand one: " << endl;
cin >> operand1.i;
cout << "Input real part for operand two: " << endl;
cin >> operand2.r;
cout << "Input imaginary part for operand two: " << endl;
cin >> operand2.i;
cout << "\nThe sum is ";
result.add(operand1, operand2);
result.print();
cout << "\nThe difference is ";
result.subtract(operand1, operand2);
result.print();
}

Related

How to multiply/divide one function to another ? How to use parameters?

How do I multiply a function to another function? and how do I properly use parameters?
I'm not exactly sure, I am really new to C++ with only about 14 weeks of class time.
Something I've tried would be creating a new function meant to multiply other functions and in the arguments I would put in the functions names.
For example:
float mealMath(numberOfAdults, mealChoosing){
//Rest of function
}
but I always get an error.Please explain how to fix this, this is a big obstacle in programming for me and I can't seem to grasp how to fix this or go about doing these things. Don't be to harsh on me for this.Thanks!
int numberOfAdults(){
int totalAdults;
cout << "Now how many adults will there be?: ";
cin >> totalAdults;
cout << "It seems there will be: " << totalAdults << " Adults." << endl;
while(totalAdults < 1){
cout << "Sorry there has to be a minimum of 1 adult!" << endl;
cout << "How many adults: ";
cin >> totalAdults;
}
return 0;
}
int numberOfKids(){
int totalKids;
cout << "Now how many Kids will there be?: ";
cin >> totalKids;
cout << "It seems there will be: " << totalKids << " kids." << endl;
while(totalKids < 0){
cout << "Sorry there has to be a minimum of 1 Kid!" << endl;
cout << "How many Kids: ";
cin >> totalKids;
}
return 0;
}
float mealChoosing(){
float cost;
string mealChoise;
cout << " " << endl;
cout << "Now, What meal will you be getting(D/S): ";
cin >> mealChoise;
if(mealChoise == "D"){
cout << "It seems you have selected the Deluxe Meal plan for everyone!" << endl;
cost = 25.95;
}
if(mealChoise == "S"){
cout << "It seems you have selected the Standard Meal plan for everyone!" << endl;
cost = 21.75;
}
cout << " " << endl;
return cost;
}
One expected result is I want to multiply the input that the user gives in function "numberOfAdults" to the input a user gives for "mealChoosing"
So I want numberOfAdults * mealChoosing but I want that done in a different function so
"float total(){
float totalBill;
totalBill = numberOfAdults * mealChoosing;
cout << totalBill;"
or something along those lines. I can't complete this project because I can't for some reason properly give the functions the proper information needed in parameters.
In this case(and most) you should not declare a function whose parameters are functions. Instead declare mealMath with an integer and a float input:
float mealMath(int a, float b){/*Your code here*/}
And then later call mealMath with the other two functions passed as arguments.
float x = mealMath(numberOfAdults(), mealChoosing());
Alternatively you can have no function parameters for mealMath() and instead call numberOfAdults() and mealChoosing() from inside of the function.
It's important to note that most of the time you'll be calling a function and using its output as an argument, and therefore you'll need to put the () after the function's identifier, instead of just typing the identifier alone.
Like mealChoosing() return totalAdults and totalKids (although its not needed here) from numberOfAdults(), numberOfKids() respectively.
int numberOfAdults() {
//...
return totalAdults;
}
int numberOfKids() {
//..
return totalKids;
}
float mealChoosing() {
//..
return cost;
}
Now on mealMath(numberOfAdults, mealChoosing)
float mealMathOutput = mealMath(numberOfAdults(), mealChoosing());

C++ calculator displays and extra 0 in the end

I am having this problem with my calculator I made. See, when I type in a calculation it always adds a 0 to the end. I don't know how to fix this do you have any ideas?
Here's the code:
#include <iostream>
using namespace std;
void Input(float &x, float &y);
float a = 1.0, b = 1.0, result;
char op;
int main() {
cout << "Welcome to Foxy's calculator" << endl;
cout << "----------------------------" << endl;
cout << "Please input a calculation operation (eg. 1+1): ";
cin >> a >> op >> b;
Input(a, b);
cout << result << endl;
system("pause");
return 0;
}
void Input (float &x, float &y) {
a = x;
b = y;
switch (op)
{
case '+':
cout << x + y;
break;
case '-':
cout << x - y;
break;
case '*':
cout << x*y;
break;
case '/':
cout << x / y;
break;
default:
cout << "Error! Operator is not correct" << endl;
cout << "Please input your calculation with a proper operator: ";
cin >> a >> op >> b;
}
}
result is a global static variable that gets zero - initialized and is never changed. So cout << result << endl; will always print "0". To fix this you should make a, b, result and op local to main (global variables are bad), pass a, b andop to calculating function and store returned calculation result in result. It will look something like this:
float result = Input(a, b, op);
cout << result << endl;
You call cout << result << endl; in the caller. and result is always 0. This is because it is never explicitly set to anything and the C++ compiler kindly zero-initialises it since it's at global scope.
In such instances, your line by line debugger is your best friend. The fact that you've mashed up your 1) input, 2) calculation, and 3) output stages is not helping: ideally they should all be separate parts of your program.
Remove cout << result << endl;

How to call user defined functions in C++?

Below you will find my dismal attempt to create a user defined function. I am trying to do an assignment that calculates the area and cost of installing carpet for various shapes. I am also suppose to keep a running total of them. In addition the assignment requires that I use a used defined function. Right now all it does is accept the input of 1 and ask "What is the length of the side: ". It then loops back to the selection menu. It does not calculate a total much less keep track of the total. What am I doing wrong in creating the user defined function and how can I incorporate it to keep a running total till they exit?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
void square(double);
const double UNIT_PRICE = 2.59;
const double LABOR_COST = 32.5;
const double PIE = 3.14;
const double TAX = .0825;
int main() {
int selection;
int sqrSide = 0;
// declare and initialize the variables for the shape
int sqrTot = 0;
do {
// get input from user as to what they want to do
cout << "Carpet Area Shape" << endl;
cout << "1. Square" << endl;
cout << "2. Rectangle" << endl;
cout << "3. Circle" << endl;
cout << "4. Triangle" << endl;
cout << "5. Done" << endl;
cout << "Type a number to continue: ";
cin >> selection;
cout << endl;
// loop through the solutions based on the user's selection
switch (selection) {
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
case 2:
case 3:
case 4:
case 5: // exit
system("cls");
break;
default:
"You have made an invalid selection. Please choose a number from the "
"list.";
cout << endl;
}
// loop through if the user is still making a valid selection
} while (selection != 5);
system("pause");
return 0;
}
void square(double) {
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
// get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
When you declare the prototype of the function you can omit the parameter but in the implementation you must place it.
change:
void square(double)
{
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
//get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
to:
void square(double sqrSide)
{
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
//get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
and also change:
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
to:
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
system("pause");
break;
As mentioned by πάνταῥεῖ in a comment, it seems that you've a few misconceptions regarding scope of variables, about parameters and about return values. Let's see if we can't dispel some of those.
First of all, lets talk about scope. When we declare a variable inside a block delimited with { and }, the variable only exists inside that block. Code that follows the block cannot access the variable.
So, this is okay:
int a = 3;
int b = 2;
int c = a*b;
But, this is not, since the values of a and b are no longer available:
{
int a = 3;
int b = 2;
}
int c = a*b;
Next, lets talk about parameters. These are the inputs to functions which the function will use in order to complete its task. While their name is irrelevant and essentially meaningless, it will certainly help you and others of you give them meaningful names. Some programming languages and indeed, students of some disciplines don't follow this maxim and can produce code that's harder to follow than it need be. The implementation of Basic found in 20 year old Texas Instruments calculators and physicists, I'm looking at you!
Consider the following functions, (whose bodies I've ommitted for brevity):
double calcArea(double a)
{
...
}
double calcArea(double b)
{
...
}
They both suck. What's a stand for, how about b?
A far better pair might resemble:
double calcArea(double radius)
{
...
}
double calcArea(double sideLenOfSquare)
{
...
}
Lastly, lets talk about return values. In each of the 4 preceding functions, the declaration begins with double. This means that we can expect to get back a value of type double from the function. However, this is just coding - there's no magic and as such, we need to actually let the compiler know what this value will be. Extending the two previous functions, we might come up with some something like the following:
double calcArea(double radius)
{
return 3.1415926535 * (radius * radius);
}
double calcArea(double sideLenOfSquare)
{
return sideLenOfSquare * sideLenOfSquare;
}
Now as it turns out - even these two simple functions are not all they've cracked-up to be. Namely, the first function uses a constant - π (Pi or 3.141....) This already exists (and with far better precision than I've used) in the math.h header file. If this file is included, we then have access to the #defined constant, M_PI.
Next, both of these functions have the same name and take the same number of parameters of identical type. The compiler can't possibly know which one you'd like to invoke. At a minimum, they should have different names. Perhaps something like calcCircleArea and calcSquareArea. Now, the compiler knows which function you're referring to and will happily compile this part of the code. Errors may exist elsewhere, but these are a different matter.
A little research on function overloading will provide resources that can explain the problem and solution to functions with the same name far better than I am both able and inclined to try. :)

Find compound interest using operator overloading

I am writing a code that tries to find out the simple and compound interest using operator overloading.
While I have found the simple interest, I am having problem with the compound interest.
#include<iostream>
#include<iomanip>
using namespace std;
class Interest
{
private:
double P;
double R;
double I;
public:
Interest(){};
~Interest(){};
void setP(double recieveP){P = recieveP;}
void setR(double recieveR){R = recieveR/100;}
double getP(){return P;}
double getI(){return I;}
Interest operator*(int T)
{
class Interest int1;
int1.I= P*R*T;
return int1;
}
};
int main()
{
class Interest simp1;
class Interest comp1;
double Principle,Rate,Years;
cout << "Enter the Principle Amount" << endl;
cin >> Principle;
simp1.setP(Principle);
comp1.setP(Principle);
cout << "Enter the Rate Amount" << endl;
cin >> Rate;
simp1.setR(Rate);
comp1.setR(Rate);
cout << "Enter the number of years:";
cin >> Years;
simp1 = simp1*Years;
cout << "The Simple Interest is: " << simp1.getI() << endl;
for(int i =0; i < Years; i++)
{
comp1 = comp1*1;
comp1.setP(comp1.getI()+comp1.getP());
}
cout << "The compound Interest is: " << comp1.getI() << endl;
return 0;
}
No matter what I enter the values for the compound Interest is always zero.
When you create object Interest int1 in operator *, you set only it's I value. P and R are uninitialized, so the have trash value, like 1.314e-304. You must copy values from the source:
Interest operator*(int T)
{
class Interest int1;
int1.P = P;
int1.R = R;
int1.I= P*R*T;
return int1;
}
You also should set default values for your class members in default constructor, to avoid future mistakes:
Interest() : P(0.0), R(0.0), I(0.0)
{
};

C++ Structs Not Compiling... Not Initialized Properly? Not using them right?

I am -trying- to use nested structs/structures, and after several hours of pseudocode and attempts, the final result that I come up with doesn't work or doesn't compile.
I would like to take two vectors A and B, and compare them against each other. I set up nested struct to read the start and end point of the vector, and the vector struct itself. So I think I may be doing some wrong further below, but I am stuck.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
struct Point // Reads in three coordinates for point to make a three dimensional vector
{
double x;
double y;
double z;
};
struct MathVector // Struct for the start and end point of each vector.
{
Point start;
Point end;
};
Point ReadPoint()
{
Point pt; // Letter distinguishes between vector A and vector B, or "letterA" and "letterB"
double x, y, z;
cout << "Please input the x-coordinate: " << endl;
cin >> pt.x;
cout << "Please input the y-coordinate: " << endl;
cin >> pt.y;
cout << "Please input the z-coordinate: " << endl;
cin >> pt.z;
return pt;
}
void DotProduct (MathVector letterA, MathVector letterB, double& a_times_b ) //formula to compute orthogonality
{
a_times_b = (letterA.end.x - letterA.start.x)*(letterB.end.x - letterB.start.x) + (letterA.end.y - letterA.start.y)*(letterB.end.y - letterB.start.y) + (letterA.end.z - letterA.start.z)*(letterB.end.z - letterB.start.z);
}
int main()
{
MathVector letterA;
MathVector letterB;
double a_times_b;
letterA = ReadPoint();
letterB = ReadPoint();
DotProduct (letterA, letterB, a_times_b);
cout << "The vector " << letterA << " compared with " << letterB << " ";
if ( a_times_b == 0)
cout << "is orthoganal." << endl;
else
cout << "is not orthoganal." << endl;
return 0;
}
One problem is with your ReadPoint whose return type is Point, but you're returning an instance of MathVector. Also, you read the input into variables which ignore eventually.
You should write ReadPoint as:
Point ReadPoint()
{
Point p;
cout << "Please input the x-coordinate: " << endl;
cin >> p.x;
cout << "Please input the y-coordinate: " << endl;
cin >> p.y;
cout << "Please input the z-coordinate: " << endl;
cin >> p.z;
return p;
}
Or a little better version:
Point ReadPoint()
{
Point p;
cout << "Please enter point-coordinate : " << endl;
cin >> p.x >> p.y >> p.z; //example input : 1 2 3
return p;
}
Or, still better is, overload >> operator as:
std::istream & operator>>(std::istream & in, Point & p)
{
cout << "Please enter point-coordinate : " << endl;
return cin >> p.x >> p.y >> p.z; //example input : 1 2 3
}
//Use this as
Point pointA, pointB;
cin >> pointA >> pointB;
Now read a good C++ book. If you're already reading one, then make sure it is really good. Here is a list of really good C++ books, of all levels:
The Definitive C++ Book Guide and List
ReadPoint returns letter of type MathVector instead of Point
You haven't overloaded operator << to tell it how to handle MathVector objects
letterA and letterB are of type MathVector
MathVector letterA;
MathVector letterB;
double a_times_b;
letterA = ReadPoint();
letterB = ReadPoint();
you should create another method to read Mathvector.. as you are doing with Point.
and in method ReadPoint
return type must be Point .. If you reading point then do calculation here to create the object of MathVector go tet startpoint and endpoint format.
Point ReadPoint()
{
MathVector letter; // Letter distinguishes between vector A and vector B, or "letterA" and "letterB"
double x, y, z;
cout << "Please input the x-coordinate: " << endl;
cin >> x;
cout << "Please input the y-coordinate: " << endl;
cin >> y;
cout << "Please input the z-coordinate: " << endl;
cin >> z;
return letter;
}
You didn't explain what it is you're trying to do or what errors you got, but this code makes no sense. You have three variables, x, y, and z. You fill them with values you get from the user. Then you don't do anything with those variables and return the MathVector created by a default constructor even though you say you're going to return a Point. That makes very little sense.
No match for 'operator=' error means that there's no function for assigning a MathVector to a Point. You are calling ReadPoint() which returns a Point and trying to assign the returned value to a variable of type MathVector. The compiler can't create a 'convertion' function automatically. You have to provide one yourself. Perhaps what you meant was
letterA.start = ReadPoint();
letterA.end = ReadPoint();