I am playing around with classes in C++. Currently I am working on a class for complex numbers and want to be able to print them in the following format: -2+3i
, 1-4i
. That means, that I want the real part to have only a sign if it is negative. In contrast the imaginary part should have always a sign whether it is positive or negative.
I tried the following which did not work as expected:
inline void Complex::print() const {
std::cout << x;
std::cout << std::showpos << y << "i" << std::endl;
}
This method prints also for the real part the sign if it is positive. Why does std::showpos
affect the first line?
Is there any better way to do that?
if (real < 0)
etc. Sidenote: Instead of calling the componentsx
andy
, it would make more sense to refer to them asreal
andimaginary
, especially since that's what you do when you're speaking – byxorstd::complex
would be the way to go, and the current title for sure will attract users seeking for how to printstd::complex
– 463035818_is_not_a_number