1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
// assuming we want to print "4x^2"
// 'num' is the 4
// 'var' is the "x^2"
// first is true if this is the first monomial in the polynomial
// and is false otherwise.
//
// note first is passed by reference and is changed by the function
// the function will set it to false if this monomial is printed
void PrintMonomial(int num,const char* var,bool& first)
{
// if the num is zero, we have nothing to print
if(!num)
return;
// see if the number is negative. If so, make it positive
// but keep track of the sign
bool neg = (num < 0);
if(neg)
num = -num; // num is now always positive
// we will need different logic if this is the first
// monomial or not. IE:
// " + 3x" vs. "3x" or
// " - 3x" vs. "-3x"
if(first)
{
// print the sign only if it's negative
if(neg) cout << '-';
first = false; // now set 'first' to false so that future monomials are not printed as the first
}
else
{
// here we need to put spaces before and after the +/-
if(neg) cout << " - ";
else cout << " + ";
}
// now, just print the number if it's > 1
if(num > 1) cout << num;
// and print the variable and exponent
cout << var;
}
// now the rest is simpe
int main()
{
int a, b, c;
// ...get a,b,c from user here...
bool first = true;
PrintMonomial(a,"x^2",first);
PrintMonomial(b,"x",first);
PrintMonomial(c,"",first);
// as an added bonus, if a,b,c were all zero, nothing was printed, so 'first' will still be true here
if(first)
cout << "0";
return 0;
}
|