[Solved] Don’t print variable if it’s zero


I don’t think you can avoid doing the condition and printing if non-zero somewhere.

About all you can do is wrap it up so most code doesn’t need to deal with it:

class complex { 
   double x;
   double i;
public:
    // ...

    friend std::ostream &operator<<(std::ostream &os, complex const &c) { 
        // if both parts are 0, we probably want to print *something*
        if (c.x == 0.0 && c.i == 0.0)
            return os << 0;
        if (c.x != 0.0)
            os << c.x;
        if (c.i != 0.0)
            os << c.i << "i";
        return os;
     }
};

complex a, b, c;

// ...
cout << a << operation << b << " = " c << "\n";

You’ll have to add a little more if you want this to honor (for example) width/precision correctly (though for real use, you undoubtedly want to use the complex class that’s already in the standard library instead).

solved Don’t print variable if it’s zero