I'm studing structures, in the fallowing code my teacher created a structure of the complex numbers (numbers that are formed by two parts: a real one and an imaginary one).
#include <iostream>
#include <cmath>
#ifndef COMPLEX_DATA_H
#define COMPLEX_DATA_H
struct complex_data
{
double re = 0; // real part
double im = 0; // immaginary part
};
#endif
int main()
{
std::cout << "Insert two complex numbers (re, im): ";
complex_data z1, z2;
std::cin >> z1.re >> z1.im;
std::cin >> z2.re >> z2.im;
... // the code continues
}
I'd like to ask two questions:
Leaving z1 and z2 uninitialized will cause any trouble considering they're inside a function and their default inizialitation is undefined?
How can we write the actual form of a variable that is a complex number?
In reality is something like this c = 3 + 2i.
But if we write it, the computer will sum it because it don't know the difference between real numbers and imaginary ones. So we'll be forced to use a string, but in this case it'll become a sequence of charcaters! Any idea?
Using Ubuntu 14.04, g++ 4.9.2.
Since C++11, you have User defined literal (and since C++14 you have the standard literal operator ""i for the pure imaginary number of std::complex<double>).
You may write your own operator ""_i for your custom struct complex_data and also operator + to have what you expect, something like:
constexpr complex_data operator"" _i(unsigned long long d)
{ return complex_data{ 0.0, static_cast<double>(d) }; }
Live example.
Q1- Constructors are meant to intialize the member variables use them.
Q2- Actual Form can be written using strings its just matter of displaying.
c = 3 + 2i.
Compiler really dont know this, you can overload + operarator.
if you define + operator addition will be performed. (whatever code is written in that function e.g real+= a.real;)
Related
I have write this code to solve a quadratic formula but it doesn't work when the answer is complex(in iota form like 3i or √-3) i want to get answer in iota how could i manage it
#include<iostream>
#include<math.h>
using namespace std;
int main(){
float a,b,c,variable1,variable2,variable3,y,x,variable4;
cout<<"Enter a:";
cin>>a;
cout<<"Enter b:";
cin>>b;
cout<<"Enter c:";
cin>>c;
variable1=-b;
variable2=b*b;
variable3=(4*a*c);
variable4=(variable2-variable3);
y=sqrtf(variable4);
x=(variable1+y)/2;
cout<<"x=" <<x <<endl;
}
The overload of std::sqrt that produces a complex result is declared in <complex> and takes a std::complex<T> as its argument, so to get a complex result, you need to start with a complex input, and include the correct header.
Here's a trivial example:
#include <complex>
#include <iostream>
int main() {
std::complex<double> d{ -1, 0 };
std::cout << std::sqrt(d);
}
Result:
(0,1)
Those represent the real and imaginary parts respectively, so this is 0+1i, as we'd expect.
It may also be worth noting that starting with C++ 14, the standard library defines a user-defined literal for imaginary numbers, so you could initialize d like this:
using namespace std::literals;
auto d = -1.0 + 0i;
This produces the same result, but for people accustomed to writing a complex number as a + bi, it may look a little more familiar/comfortable. The one "trick" is that it's still doing type deduction, so to get a complex<double>, you need to use -1.0 instead of -1 (which I guess would try to deduce a std::complex<int>).
I am trying to do a simple library where the object is a point on the xy-axis.
I want to be able to use literals like this:
Point a = (3,4);
where (3,4) is a point literal.
I read about user defined literals, but (as I understood) this seems to be impossible.
May be "(3,4)"_P is possible as I understand it.
However, I found on this page interesting use of user defined literals as follows:
#include <iostream>
#include <complex>
int main()
{
using namespace std::complex_literals;
std::complex<double> c = 1.0 + 1i;
std::cout << "abs" << c << " = " << abs(c) << '\n';
}
I can under stand the part 1i as a user defined literal, but not the whole thing 1.0 + 1i.
What I am missing, and what is the nearest possible way of getting a literal similar to (x,y) without using ".
As Some programmer dude shows, the best way is to use uniform initialization.
However, just for the fun of it, you can (sort of) do this with User Defined Literals. My idea is to to have 2 literals for each coordinate and overload operator+ between them to create the point.
Remember, this is just for fun, don't use this in a real code:
struct Px { int x; };
struct Py { int y; };
struct Point {
int x;
int y;
};
constexpr auto operator""_px(unsigned long long x) -> Px { return Px{(int)x}; }
constexpr auto operator""_py(unsigned long long y) -> Py { return Py{(int)y}; }
constexpr auto operator+(Px x, Py y) -> Point { return Point{x.x, y.y}; }
then you can have:
auto p = 3_px + 4_py; // p is deduced to type `Point`
Of course this is just a rough framework. Read this great article to learn more about UDLs. You would need to deal with the narrowing conversion in a better way and propper use namespaces to make it a better solution.
As a bonus, you could also use operator, to create a syntax more appropriate to what you had in mind. But, don't do this, as overloading operator, is just evil:
auto operator,(Px x, Py y) -> Point { return Point{x.x, y.y}; }
auto p = (2_px, 1_py); // p is deduced to type `Point`
You can't make up literals on your own, only create suffixes for literals. Like the shown 1i or the standard language f as in 1.0f. (See e.g. this user-defined literal reference for more information.)
What you can to is to use uniform initialization doing something like
Point a = { 3, 4 }; // note the use of curly-braces
Depending on what Point is you might need to add a suitable constructor to make it work.
You have 3 options
Point p = { 1,2 };
Point p2{ 1,2 };
Point p3(1,2);
I have code which has a lot of conversions from double to int . The code can be seen as
double n = 5.78;
int d = n; // double implicitly converted to a int
The implicit conversion from double to int is that of a truncation which means 5.78 will be saved as 5 . However it has been decided to change this behavior with custom rounding off .
One approach to such problem would be to have your own DOUBLE and INT data types and use conversion operators but alas my code is big and I am not allowed to do much changes . Another approach i thought of was to add 0.5 in each of the numbers but alas the code is big and i was changing too much .
What can be a simple approach to change double to int conversion behaviour which impact the whole code.
You can use uniform initialization syntax to forbid narrowing conversions:
double a;
int b{a}; // error
If you don't want that, you can use std::round function (or its sisters std::ceil/std::floor/std::trunc):
int b = std::round(a);
If you want minimal diff changes, here's what you can do. Please note, though, that this is a bad solution (if it can be named that), and much more likely leaving you crashing and burning due to undefined behavior than actually solving real problems.
Define your custom Int type that handles conversions the way you want it to:
class MyInt
{
//...
};
then evilly replace each occurence of int with MyInt with the help of preprocessor black magic:
#define int MyInt
Problems:
if you accidentally change definitions in the standard library - you're in the UB-land
if you change the return type of main - you're in the UB-land
if you change the definition of a function but not it's forward declarations - you're in the UB/linker error land. Or in the silently-calling-different-overload-land.
probably more.
Do something like this:
#include <iostream>
using namespace std;
int myConvert (double rhs)
{
int answer = (int)rhs; //do something fancier here to meet your needs
return answer;
}
int main()
{
double n = 5.78;
int d = myConvert(n);
cout << "d = " << d << endl;
return 0;
}
You can make myConvert as fancy as you want. Otherwise, you could define your own class for int (e.g. myInt class) and overload the = operator to do the right conversion.
I'm looking for a function that returns a reference to real or imag values of a complex number in C++11. In C++03 I could say:
complex<double> C; cin >> C.real();
But in C++11 that gives me a compile error since the C.real() returns a value not a reference.
I found out that I can write this:
double t; cin >> t; C.real(t);
but it isn't straightforward and for example if I want to multiply the real part of c by 2 and ad it by 1 I should say:
C.real(2*C.real() + 1);
That is not clean.
Is there any other [clean] way to do that?
If you really want to separate input for real and imaginary parts of a complex, you could try IO manipulators approach.
#include <complex>
#include <iosfwd>
class proxy_complex {
explicit proxy_complex(std::istream& strm, bool f)
: strm_(&strm), flag(f) { }
proxy_complex(const proxy_complex&) = default;
std::istream* strm_;
bool flag; // flag to check whether we're writing real or imag
public:
template<typename T>
std::istream& operator>>(std::complex<T>& c)
{
T n;
if (*strm_ >> n)
flag ? c.real(n) : c.imag(n);
return *strm_;
}
friend proxy_complex operator>>(std::istream& is, proxy_complex(*func)(std::istream&))
{
return func(is);
}
friend proxy_complex real(std::istream&);
friend proxy_complex imag(std::istream&);
};
inline proxy_complex real(std::istream& is)
{
return proxy_complex(is, true);
}
inline proxy_complex imag(std::istream& is)
{
return proxy_complex(is, false);
}
You can put the above code in a header file of its own (if you do that, it might be a good idea to wrap it in a namespace).
Usage:
#include <iostream>
#include "my_header.h"
int main()
{
std::complex<double> c;
std::cin >> real >> c >> imag >> c;
if (std::cin) std::cout << c;
}
Hope I guessed your definition of "clean" correctly :)
Sorry to be negative, but your question starts from a wrong premise. Concerning std::complex the 2011 standard is backward compatible. Code of the form
complex<double> C; cin >> C.real();
was never valid C++. The 2003 standard only gives the member function
T std::complext<T>::real() const;
but not
const T& std::complext<T>::real() const; // non-standard
T& std::complext<T>::real(); // non-standard
even though some implementations (such as that shipped with gcc 4.3) may have implemented these two instead.
Now, to answer your question. Clearly, the cleanest way is to follow the intention of the standard. The 2011 standard adds the following setters
void std::complex<T>::real(T);
void std::complex<T>::imag(T);
so you can now simply use those to set the real or imaginary parts separately.
However, those cannot be used in a function taking T&, such as operator>>. For that you must do some nasty tricks like
template<typename T>
inline T& get_real(std::complex<T>&z) { return reinterpret_cast<T(&)[2]>(z)[0]; }
template<typename T>
inline T& get_imag(std::complex<T>&z) { return reinterpret_cast<T(&)[2]>(z)[1]; }
std::complex<double> z;
cin >> get_real(z) >> get_imag(z);
Actually, as pointed out in a comment by bames53, the standard guarantees std::complex to be laid out such that this always works.
C++11 now allows
double& re(std::complex<double>& c)
{
return reinterpret_cast<double (&)[2]>(c)[0];
}
double& im(std::complex<double>& c)
{
return reinterpret_cast<double (&)[2]>(c)[1];
}
const double& re(const std::complex<double>& c)
{
return reinterpret_cast<const double (&)[2]>(c)[0];
}
const double& im(const std::complex<double>& c)
{
return reinterpret_cast<const double (&)[2]>(c)[1];
}
Usage:
std::complex<double> a;
std::cin >> re(a);
Relevant quote §26.4:
Moreover, if a is an expression of type cv std::complex<T>* and the expression a[i] is well-defined for an integer expression i , then:
— reinterpret_cast<cv T*>(a)[2*i] shall designate the real part of a[i], and
— reinterpret_cast<cv T*>(a)[2*i+1] shall designate the imaginary part of a[i] .
If you want to manipulate real parts you can just use double or floats directly.
If you want to manipulate imaginary parts you can have a unique complex number std::complex<double> I(0,1) and multiply it by the value you want.
For instance, instead of writing: C.real(2*C.real() + 1); you can write: C += C.real() + 1;
Then you can mix doubles with complexs in your mathematical expressions and the compiler will use the correct conversions. See an example:
#include <iostream>
#include <complex>
int main(int argc, char* argv[])
{
// Let the user enter a Real number
double c;
std::cin >> c;
// Explicitly convert to a complex
std::complex<double> C = 2*c + 1;
std::cout << C << std::endl;
// Creates a pure imaginary complex number I
std::complex<double> I(0,1);
// Mix together complex and real numbers in the
// same expression
C = C + c*I;
std::cout << C << std::endl;
// Setup a specific value and compare how to achieve
// C.real = 2*C.real + 1
C = 1. + 2.*I;
C.real(2*C.real()+1);
std::complex<double> D = 1. + 2.*I;
D += D.real() + 1;
std::cout << "C=" << C << "\tD=" << D << std::endl;
return 0;
}
The output:
$ ./main.exe
1
(3,0)
(3,1)
C=(3,2) D=(3,2)
$ ./main.exe
2
(5,0)
(5,2)
C=(3,2) D=(3,2)
If you are afraid of the lost of efficiency of this method compared to affecting directly through a reference you can look at the generated assembly code. On my computer with g++ and -O3 everything is inlined.
Not that I know of.
You could construct a helper if that's important to you:
class ModifyReal
{
double d;
complex<double> & c;
public:
ModifyReal(complex<double> & c_) : c(c_), d(numeric_limits<double>::quiet_NaN())
{}
operator double &() { return d; }
~ModifyReal() { c.real(d); }
};
cin >> ModifyReal(C);
I would not exactly recommend to use this, however, unless you have a very compelling reason to. ("I do not like it" is not convincing enough.)
I do think having many different classes like this in your code can hamper readability, but if you use it in a few dedicated instances you should be fine. Error handling can become subtley difficult (e.g. since cin doesn't throw on invalid input, C gets assigned nan, rather than being unmodified.)
What does "clean" mean? No, don't tell me - think about it.
Inspired by Steve Jessop, it's just C += (C + C.conj())/2 + 1;.
Remember that in complex math, you cannot really treat the real and imaginary parts as fully independent components. That's just about as sane than treating their phase and magnitude as fully independent components. Addition of complex numbers is done independently on real and imaginary parts, but multiplication is done independently on the phase and magnitude parts.
Your example is not complex multiplication, so it makes sense that std::complex doesn't support that kind of multiplication.
I am a newbie at C++, and I am trying to make a "calculator" which: adds two numbers, subtracts two numbers, multiplies two numbers, divides two numbers, takes the sine of a number, takes the cosine of a number, or takes the tangent of a number. Here is the code:
#include <iostream>;
#include <cmath>;
#include <string>
int main ()
{}
int ask(std::string operation);
{
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std::cin>>operation;
if (operation="Addition")
{
goto Add
}
float Add(float addend1, float addend2, float answer)
{
Add:
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
break
}
}
There will be more functions later, but my problem is on line 7. There is an error that says: expected unqualified-id before "{" token. I know my indentation is horrible, but thanks!
You have a lot of issues in your code.
First, as Ivan points out, you are trying to define a function inside of a function (ask() inside main()). That isn't valid.
Second, you have a goto (why?!) attempting to jump to a label in another function. I doubt your compiler will even allow that, but how would you expect that to work? You are attempting to use variables passed to your function addition that don't exist as you never call the function and the stack has never been setup for it. This is bad, don't do it, just call the function properly.
Third, the #include preprocessor directive is terminated with a newline, not a semicolon. That could cause some (relatively) hard to track down compilation errors.
Fourth, you are mistakenly attempting to assign the const char* "Addition" to operation when what you meant to use was the equality operator ==. That won't work ether though because operation is an r-value and cannot be assigned to like that. If you want to modify it you will need to declare it as a pointer, but once again, that's not what you are going for semantically...
If you want to compare strings and (for whatever reason...) are intent on using pointers to char then you should be using strcmp. That said, you are in C++ land, so just use std:string instead.
Try something like this. I haven't enhanced your code in anyway, just made it something that will compile and run. I have made a few changes.
Aside from getting rid of a few syntax errors, your original Add function took the result as a float argument. Assigning to that from within the function would only modify a copy. You would need to take a pointer or reference if you want the caller to see the modified value, but you don't need that at all as you can simply return the result.
The string comparison is case sensitive, so you would probably want to change it to be case insensitive. I'm assuming no localization here :). I'm not performing error checking on the input either, so be aware that it may fail if the user enters something other than a valid floating point number.
#include <iostream>
#include <string>
using namespace std;
void Ask();
float Add( float, float );
int main( size_t argc, char* argv[] )
{
Ask();
return 0;
}
void Ask()
{
cout << "Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
string operation;
cin >> operation;
if( operation == "Addition" )
{
float first = 0, second = 0;
cout << "enter first operand";
cin >> first;
cout << "enter second operand";
cin >> second;
cout << "The result is: " << Add( first, second );
}
}
float Add( float first, float second )
{
return first + second;
}
С++ doesn't allow nested functions. You have function main() and trying to declare function ask() inside it. And compiler doesn't know what you want.
I commented your code a little bit, maybe that gets you started:
#include <iostream>;
#include <cmath>;
#include <string>;
int main () {
int ask (){ //you cannot nest functions in C++
char operation [20]; //why not use the string class if you include it anyway
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std:cin>>operation;
if (operation="Addition"){ //you cannot compare char-strings in C++ like that
goto Addition; //don't use goto (I don't want to say "ever", but goto is only used in extremely rare cases) make a function call instead
}
}
float addition(float addend1, float addend2, float answer) //you probably want to declare the variables inside the function
{
Addition: //don't use labels
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
}
Let's try to break this down..
You shouldn't use ; on the precompiler directives.
#include <iostream>;
#include <cmath>;
#include <string>;
Should be
#include <iostream>
#include <cmath>
#include <string>
.
int main () {
int ask (){
See Ivans answer for this
char operation [20];
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std:cin>>operation;
if (operation="Addition"){
You can use std::string instead which is alot easier to deal with. Then you can write
#include <string>
...
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std::string myString;
getline(cin, myString);
if (myString == "Addition"){
.
goto Addition;
}
}
float addition(float addend1, float addend2, float answer)
{
Not sure what is going on here.. but let's break Addition to it's own function
void Addition(){
// do addition here
}
.
Addition:
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
}
Don't forget that you have to define the variables
int addend1;
int addend2;
int answer;
Hope this helps you along the way.
First int ask() what is that.Why do you start a block here.
Second you have two {s and three }s that's because of the ask().
I think that c++ does not support anonymus functions.
Third why do you use goto,when you have a function,just call the function.
Fourh your addition func should either be void or remove it's last parameter.
Also I think that you don't need string.h file unless you use some rather advanced funcs,the char array should be enough for your program.