How to use Complex numbers in Class/Object C++ - c++

Im strugling to implement complex numbers into my code. When I compile it gives me random numbers. It should use imaginary number i = sqrt(-1). It should output realPart + imaginaryPart * i.
#include <iostream>
#include <complex>
using namespace std;
class Complex
{
private:
double i;
complex<double> imaginarypart = i*sqrt(1);
double realpart;
public:
void seti(double a1) {
i = a1;
}
void setrealpart(double a2) {
realpart = a2;
}
void printwhole() {
cout << realpart + imaginarypart;
}
};
int main()
{
double a, b;
cout << "Enter your realpart" << endl;
cin >> a;
cout << "Enter your imaginarypart " << endl;
cin >> b;
Complex num1;
num1.seti(b);
num1.setrealpart(a);
cout << endl;
num1.printwhole();
}

The point is that an the type double cannot store imaginary values.
Yet you try to do so, e.g. with sqrt(1); (though you probably meant -1).
The complex<double> is indeed able to store imaginary values, but on the one hand it won't work by assigning the product of the non-initialised i with 1 and on the other hand you seem to try to implement complex numbers yourself. Using the provided complex standard type somewhat defeats that. If you use it, then you just need to learn outputting it in the format you want, instead of doing all the implementation work.
Lets assume that you are more interested in getting it done yourself first.
What you need to do is to always represent complex numbers as two numbers.
I hence propose to change your code likes this.
#include <iostream>
using namespace std;
class Complex
{
private:
/* double i; Won't work, it cannot store imaginary values. */
double imaginarypart;
double realpart;
public:
void setimaginarypart(double a1) {
imaginarypart = a1;
}
void setrealpart(double a2) {
realpart = a2;
}
void printwhole() {
cout << realpart << '+' << imaginarypart << 'i'; // To get the output you want.
}
};
int main()
{
double a, b;
cout << "Enter your realpart" << endl;
cin >> a;
cout << "Enter your imaginarypart " << endl;
cin >> b;
Complex num1;
num1.setimaginarypart(b);
num1.setrealpart(a);
cout << endl;
num1.printwhole();
}
Alternatively use existing solutions (e.g. std::complex), instead of trying to program one yourself. Outputting them in the shape you want (r+i*I) does not require to implement the whole thing yourself.
Have a look at https://en.cppreference.com/w/cpp/numeric/complex to learn about what it offers.

As you figured out, complex numbers have a real and an imaginary part. And in std::complex<double>, those two parts are combined.
But in your class Complex, you have Complex::i, Complex::realpart, Complex::imaginarypart::real() and Complex::imaginarypart::imag(). That's 4 parts!
Furthermore, complex<double> imaginarypart = i*sqrt(1); means that Complex::imaginarypart is set to i*sqrt(1) when a Complex object is created. But at that time, i is still uninitialized! So that won't work either. This is why you get random numbers (or a crash, depending on your luck).
The simple solution is to drop your whole class Complex. std::complex<double> already has functions to set the real and imaginary parts, namely std::complex<double>::real(double) and std::complex<double>::imag(double)
(Note: real and imag are setters if you pass a value, getters if you don't).

Related

How does the "if block" work in this code?

Please consider the following code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
int a, b;
cout << "Enter two integer: ";
cin >> a >> b;
if (a > b) {
int temp = a;
a = b;
b = temp;
}
cout << a << "<=" << b << endl;
}
The above code yields the minimum of the two inserted numbers. Can anyone explain how the if block works?
It's the idiomatic way of swapping two numbers.
There are more efficient ways: to exploit those use std::swap instead.
(The statement int temp=a; sets the variable temp to the value of a. The statement a=b; sets a to the value of b. Finally, b=temp; sets b to temp which was the original value of a. The overall effect therefore is to exchange the values of a and b.)

Having issues with void function

I'm trying to the program to display the bonus, but the programs renders an answer to 0. I am extremely new to c++ so any guidance would be greatly appreciated.
Here's the code:
#include <iostream>
#include <iomanip>
using namespace std;
//function prototypes
void enterItems(double, double);
void calcAndDisplayBonus(double &salesAmt, double &rate);
int main()
{
//declare variables
double sales = 0.0;
double bonusRate = 0.0;
//enter input values
enterItems(sales, bonusRate);
//calculate and display bonus
cout << fixed << setprecision(2);
calcAndDisplayBonus(sales, bonusRate);
system("pause");
return 0;
} //end of main function
//*****function definitions*****
void enterItems(double salesAmt, double rate)
{
cout << "Enter sales: ";
cin >> salesAmt;
cout << "Enter bonus rate (in decimal form): ";
cin >> rate;
} //end of enterItems function
void calcAndDisplayBonus(double &salesAmt, double &rate)
{
cout << "Bonus: $" << salesAmt * rate << endl;
} //end of calcAndDisplayBonus function
When you call enterItems, you are passing parameters by copy. This means that your changes won't affect the variables available in the scope of the caller.
To solve it, you can either pass a couple of references or pointers, as well as rely on a pair returned from the function as a result, and so on.
As an example, by writing:
void enterItems(double &salesAmt, double &rate)
You'll actually solve the problem above mentioned.
Another valid prototype is:
void enterItems(double *salesAmt, double *rate)
Even though this one asks for a small set of changes all around your code (the example, of course).
There is a plenty of possible solutions, hoping these ones will give you an idea of what's wrong.
Your function
void enterItems(double salesAmt, double rate)
is taking two double-parameters by value, this means, your changes you do inside the function will not be visible from the outside. You could take the doubles by reference:
void enterItems(double &salesAmt, double &rate)
but i'd prefer to return the values, but since you can only return a single value you'd need two functions:
double enterSales()
{
double tmp;
cout << "Enter sales: ";
cin >> tmp;
return tmp;
}
double enterBonus()
{
double tmp;
cout << "Enter bonus rate (in decimal form): ";
cin >> tmp;
return tmp;
}
//in your main:
double sales = enterSales();
double bonusRate = enterBonus();

Operator overloading using constructor add two Complex number

I wanted to get a value from the user via using constructor and another value will be in the program itself. I try to code it as below. But constructor is initializing all the values to 0,0(no argument). What to do?
#include<iostream>
using namespace std;
class complex
{
float x;
float y;
public :
complex() //no argument constructor
{
/* cout<<"Enter real = ";
cin>>x;
cout<<"Enter imaginary = ";
cin>>y;*/
}
complex(float real, float imag)
{
cout<<"Enter real = ";
cin>>x;
cout<<"Enter imaginary = ";
cin>>y;
x = real;
y = imag;
}
complex operator+(complex);
void display(void);
};
complex complex :: operator+(complex c)
{
complex temp;
temp.x = x + c.x;
temp.y = y+c.y;
return(temp);
}
void complex :: display(void)
{
cout<<x<<" +i"<<y<<"\n";
}
int main()
{
complex c1,c2(2.5,1.7),c3(0,0);
c3 = c1+c2;
c1.display();
c2.display();
c3.display();
system ("PAUSE");
// return 0;
}
Below is probably what you would want.
I changed your Complex number class to only use one constructor that has default parameters both will default to 0 if you do not provide any parameters.
In your code your parameter less function does nothing and defaults to just using the default constructor for x and y (in the case of floats using 0). You can combine this with the parametered constructor by using default parameters, as mentioned above.
This makes it explicit that if you don't provide values to the Complex constructor you should expect x and y to be 0.
I also added input and output stream operators, but that may not be necessary for your uses.
But it allows you to use cin >> c1; and it is apparent that you expect the user to input the values for c1, instead of embedding that code in the default constructor.
#include<iostream>
using namespace std;
class complex{
float x;
float y;
public :
// it seems like one constructor with default parameters
// should work for your case.
complex(float real = 0, float imag = 0):x(real),y(imag){}
complex operator+(complex);
friend ostream& operator << (ostream& outs, Complex C);
friend istream& operator << (istream& ins, Complex C);
};
ostream& operator << (ostream& outs, Complex C){
cout << C.x << " + i" << C.y;
return outs;
}
istream& operator << (istream& ins, Complex C){
if (ins == cin){
cout << "Enter real part" << endl;
ins >> C.x;
cout << "Enter imaginary part" << endl;
ins >> C.y;
} else {
ins >> C.x >> C.y;
}
return ins;
}
// your plus operator is fine.
int main(){
complex c1,c2(2.5,1.7),c3(0,0); //c1 will have x = 0, y = 0
c3 = c1+c2; // c3.x = 2.5, c3.y = 1.7
cout << c1 << endl; // displays 0 + i0
cout << c2 << endl; // displays 2.5 + i1.7
cout << c3 << endl; // displays 2.5 + i1.7
return 0;
}
Output:
0 + i0
2.5 + i1.7
2.5 + i1.7
If this is not what you expect for output, what would you expect?
I have made a couple of assumptions and modified your code accordingly, the assumptions are:
The second constructor constructs values from the ones present in the main function, so we need a different constructor to create object using the input
c1 contains the values entered by the user and c3 is created using default constructor
Keeping the above in mind the code can be modified as follows:
#include<iostream>
using namespace std;
class complex
{
float x;
float y;
public :
complex() {}
complex(float real, float imag) { x=real; y=imag; } //constructor for creating x and y from values given in the code
complex(istream&);//constructor for creating values entered as input
complex operator+(complex);
void display(void);
};
//definition for constructor for taking user input
complex::complex(istream& in)
{
cout<<"Enter real = ";
in>>x;
cout<<"Enter imaginary = ";
in>>y;
}
complex complex :: operator+(const complex& c) const
{
complex temp;
temp.x = x + c.x;
temp.y = y+c.y;
return(temp);
}
void complex :: display(void)
{
cout<<x<<" +i"<<y<<"\n";
}
int main()
{
complex c1(cin),c2(2.5,1.7),c3;
//note the changes, c1 is made from user input, c2 from constructor and c3 using default constructor
c3 = c1+c2;
c1.display();
c2.display();
c3.display();
}
Make note of the modifications made which I have indicated by the comment lines

Expression Must Have Class Type (Using a struct array as a function parameter)

I am writing a C++ program in Visual Studio Pro 2013, and I am having an error when trying to use a structure array as a parameter in a function call. This is my code.
struct ProcessingData
{
double latitude;
double longitude;
};
double distanceCalculator(double dataLat[], double dataLong[], double inLat, double inLong)
{
//some code in here
}
int main()
{
char userChoice;
double userLatitude;
double userLongitude;
ProcessingData dataInfo[834];
cout << "Welcome!\n"
<< "Please select which option you would like to run:\n\n"
<< "A) Calculate the distance from a specified set of coordinates.\n"
<< "B) Print out the information for all waypoints.\n\n"
<< "Please enter your selection now: ";
cin >> userChoice;
switch (userChoice)
{
case 'a': //Menu option for distance calculation
{
getTheFile(); //other function that is being used
cout << "Please enter the latitude for the coordinate you are using: ";
cin >> userLatitude;
cout << "Please enter the longitude for the coordinate you are using: ";
cin >> userLongitude;
distanceCalculator(dataInfo.latitude[], dataInfo.longitude, userLatitude, userLongitude)
}
break;
I am getting an error in my distanceCalculator function call, on the dataInfo.latitude and dataInfo.longitude that says "expression must have class type."
Why am I getting this error and how to I solve it?
The variable dataInfo is an array of ProcessingData. The class ProcessingData has a member latitude.
You seem to want to deal with an array consisting of the latitude members of the elements of dataInfo, but no such array exists. You can take a member of a struct, but you can't use the same syntax to extract that member from all elements of the array in one step.
If you want to pass an array, you have a couple of options. Passing the array is easy:
void foo(int A[])
{
...
}
int A[8];
foo(A);
The trouble is that the function has difficulty knowing the size of the array, so it is easy to go out of bounds. We can add another parameter for the size of the array:
void foo(int A[], unsigned int nA)
{
...
}
int A[8];
foo(A, 8);
or start using the standard containers:
void foo(vector<int> A)
{
...
}
vector<int> A;
foo(A);
Each instance of a ProcessingData contains one double for Latitude and one double for Longitude.
There are no arrays of double here. It seems as if you are trying to automagically "view" an array of double by selecting all the Latitude doubles from dataInfo, however it doesn't work that way.
Your simplest solution will probably be to change the function to be:
double distanceCalculator(ProcessingData data[], double inLat, double inLong)
{
// logic here using things like data[5].latitude
}

C++: Bug when trying to fill dynamic vector with double

I'm having trouble with a program I'm doing in class and even the teacher can't find the problem. We're doing a program that ask the user to enter double then when he stop, it scan the array and separate the positive and negative to put them in different arrays.
We notice that when we use float the program work for more numbers but still bug if we enter too much and if we use double it bug after only a few numbers. By bug I mean, the program do well but when it display the result there is some weird numbers in the array. Here is the code using double:
#include <iostream>
using namespace std;
void filling(double *, int &);
void sortPositiveNegative(double *, double *, double *, int, int &, int &);
void display(const double *, int);
int main () {
double * vecteur = new double;
double * positive = new double;
double * negative = new double;
int counter = 0, counterPos = 0, counterNeg = 0;
cout << "Filling of the real number vector " << endl;
filling(vecteur, counter);
cout << endl << "Display of the real number vector " << endl;
display(vecteur, counter);
cout << endl << "Sort of the positive and negative in the real number vector: " << endl;
sortPositiveNegative(vecteur, positive, negative, counter, counterPos, counterNeg);
cout << endl << "Display of the positive real number : " << endl;
display(positive, counterPos);
cout << endl << "Display of the negative real number : " << endl;
display(negative, counterNeg);
system("PAUSE");
return 0;
}
void filling (double *vecteur, int &counter)
{
bool validation;
char choice = 'Y';
do
{
do
{
validation = true;
cout << "Please enter the value of case " << counter+1 << ": ";
cin >> vecteur[counter];
if(cin.fail())
{
cerr << "The number entered is not valid." << endl;
cin.clear();
validation = false;
}
while(cin.get() != '\n'){}
}while(!validation);
counter++;
do
{
validation = true;
cout <<"Do you wish to continue? (Y/N): ";
cin >> choice;
if(toupper(choice) != 'Y' && toupper(choice) != 'N')
{
cerr << "We don't understand your choice, please try again." << endl;
cin.clear();
validation = false;
}
while(cin.get() != '\n'){}
}while(!validation);
}
while(toupper(choice)=='Y');
}
void sortPositiveNegative(double *vecteur, double *positive, double *negative, int counter, int &counterPos, int &counterNeg)
{
int i = 0;
for(i; i<counter;i++)
{
if(vecteur[i] >= 0)
positive[counterPos++] = vecteur[i];
else
negative[counterNeg++] = vecteur[i];
}
}
void display (const double *vecteur, int counter)
{
for(int i = 0; i<counter;i++)
cout << vecteur[i]<<endl;
cout << endl;
}
My teacher think it might be a memory problem but we have no idea why it's doing that.
Thanks in advance.
There is definitely a memory problem, and I don't see how using float would fix it. For example, the below line of code allocated only one double and not an array of doubles:
double * vecteur = new double;
Then, you use this vecteur as if it was an array of N elements. That triggers undefined behavior.
To fix it, you would have to allocate an array of as much values as you need. For example, let's say you need 10, then you allocate 10 like this:
double * vecteur = new double[10];
However, given that you don't know the number of elements in advance, you would need to extend the array every time you want to add an element. If you were writing this in C, I would have recommended you to use realloc(). But given that you use C++, just stick with std::vector<double>, it will manage memory automatically. For example:
#include <vector>
int main()
{
std::vector<double> vecteur; // Use vector to store array of doubles.
// Add as many elements as you want.
// Vector will resize itself if/when needed.
vecteur.push_back(.1);
vecteur.push_back(.2);
vecteur.push_back(.3);
vecteur.push_back(.4);
vecteur.push_back(.5);
}
Hope it helps. Good Luck!
double * vecteur = new double;
You allocate space for one doubile
filling(vecteur, counter);
Pass it to filling
cin >> vecteur[counter];
And fill untill user presses Y going outside of array with one element you have allocated memory for.
double vs float doesn't matter much. float is simply smaller and thus will be corrupting memory slower. But it is still corrupting memory starting from vecteur[1]
I'd suggest you to use std::vector<dobule> instead of plain pointers, and filling it with push_back
double * vecteur = new double;
double * positive = new double;
double * negative = new double;
Here you allocate exactly ONE double each time. The first item you store in your "array" is fine, but anything else after that is undefined behaviour.
The fix is to actually allocate as many items as you need:
double * vecteur = new double[MAXIMUM8NUMBER_OF_ITEMS];
double * positive = new double[MAXIMUM8NUMBER_OF_ITEMS];
double * negative = new double[MAXIMUM8NUMBER_OF_ITEMS];
Or better yet, use a standard container like std::vector.