C++ std: Making a polynomial class, how to suppress all 0 coefficients that the user inputs? -
After
I now have my polynomial class (almost complete) with integer coefficients. In this category, member displays a polynomial of functions in this form: If user input: 1, -2, 0, 4 then the function is called "p (x) = 1 + -2x + 0x ^ 2 + 4x ^ 3 "Which is not expected because I want to end the word 0x ^ 2 because there is 0 coefficient. It is considered to be:" p (x) = 1 + -2x + 4x ^ 3 " instead of this.
Now my "print" member function is here:
Void polynomial :: print () const {// prints the polynomial outside the simplified string plus is; Plus = "+" of each element except the first element; Int k = 0; K cout and lt; & Lt; Coefficient [0]; For (int i = 1; i & lt; coefficient.size (); i ++) {if (coefficient [i] == - 12345) break; // where -12345 to use the input cout & lt; & Lt; Plus & lt; & Lt; The coefficient [i] of the & lt; & Lt; "X"; If (coefficient [i]! = - 12345) {k ++; } If (k> 1) {court & lt; & Lt; "^" & Lt; & Lt; K; }} Cout & lt; & Lt; Endl; Return; } What else should I add to eliminate 0 coefficients?
Thanks a lot!
Change your function to do something like the following:
Zero polynomial :: Print () const {// Ignore the initial plus, but set "+" when the first period output is string plus = ""; If (coefficient [0]! = 0) {// output initial x ^ 0 coefficient. Cout & lt; & Lt; Coefficient [0]; // Make sure there are positive signs in future plus = "+"; } {Ii = 1 int i ++; i & lt; coefficient.size ()) for non zero coefficient only {//. If (coefficient [i]! = 0) {// only for output + positive if (coefficient [i]> gt;) {cout & lt; & Lt; Plus; // Output Coefficient and x Cout & lt; & Lt; Coefficient [i] & lt; & Lt; "X"; // Output exponent if 2 or more if (i> 1) COAT < & Lt; "^" & Lt; & Lt; I; // Make sure there are positive signs in future plus = "+"; }}} This will get rid of annoying and annoying + - sequences where you can just type Required - , such as Turn: x + 3x ^ 2 In:
X-3x ^ 2 This also ensures that you do not print a leading + on the first term output.
Comments
Post a Comment