【发布时间】:2010-03-10 15:46:06
【问题描述】:
好的,在读取多项式失败后,我首先尝试一种基本方法。
所以我有具有读取和打印功能的 polinom 类:
#ifndef _polinom_h
#define _polinom_h
#include <iostream>
#include <list>
#include <cstdlib>
#include <conio.h>
using namespace std;
class polinom
{
class term
{
public:
double coef;
int pow;
term(){
coef = 0;
pow = 0;
}
};
list<term> poly;
list<term>::iterator i;
public:
void read(int id)
{
term t;
double coef = 1;
int pow = 0;
int nr_term = 1;
cout << "P" << id << ":\n";
while (coef != 0) {
cout << "Term" << nr_term << ": ";
cout << "coef = ";
cin >> coef;
if (coef == 0) break;
cout << " grade = ";
cin >> pow;
t.coef = coef;
t.pow = pow;
if (t.coef != 0) poly.push_back(t);
nr_term++;
}
}
void print(char var)
{
for (i=poly.begin() ; i != poly.end(); i++ ) { //going through the entire list to retrieve the terms and print them
if (poly.size() < 2) {
if (i->pow == 0) //if the last term's power is 0 we print only it's coefficient
cout << i->coef;
else if (i->pow == 1) {
if (i->coef == 1)
cout << var;
else if (i->coef == -1)
cout << "-" << var;
else
cout << i->coef << var;
}
else
cout << i->coef << var << "^" << i->pow; //otherwise we print both
}
else {
if (i == poly.end()) { // if we reached the last term
if (i->pow == 0) //if the last term's power is 0 we print only it's coefficient
cout << i->coef;
else if (i->pow == 1)
cout << i->coef << var;
else
cout << i->coef << var << "^" << i->pow; //otherwise we print both
}
else {
if (i->coef > 0) {
if (i->pow == 1)//if the coef value is positive
cout << i->coef << var << " + "; //we also add the '+' sign
else
cout << cout << i->coef << var << "^" << i->pow << " + ";
}
else {
if (i->pow == 1)//if the coef value is positive
cout << i->coef << var << " + "; //we also add the '+' sign
else
cout << cout << i->coef << var << "^" << i->pow << " + ";
}
}
}
}
}
};
#endif
好吧,它只在读取一个术语时有效,但是当读取更多时,打印的系数是一些随机值,并且在最后一个术语之后它不应该打印“+”或“-”。
所以知道有什么问题吗?
谢谢!
最终更新
好的,我通过修改比尔的代码使它完美运行,非常感谢比尔和其他所有评论或回答的人!
这是最终的打印函数:
void print(char var)
{
list<term>::iterator endCheckIter;
for (i=poly.begin() ; i != poly.end(); i++ )
{
//going through the entire list to retrieve the terms and print them
endCheckIter = i;
++endCheckIter;
if (i->pow == 0)
cout << i->coef;
else if (i->pow == 1)
cout << i->coef << var;
else
cout << i->coef << var << "^" << i->pow;
if (endCheckIter != poly.end()) {
if (endCheckIter->coef > 0)
cout << " + ";
else {
cout << " - ";
endCheckIter->coef *= -1;
}
}
}
}
【问题讨论】:
-
添加一些断点并在调试器中运行您的程序。找出问题的最佳方法。
-
我的建议是简化很多事情。您有很多完全没有必要的“特殊情况”代码。仅举几个例子,对于一项多项式或多项式的最后一项,您不需要任何特殊的东西。
-
那么如何访问term i+1呢?我尝试了类似 i+1->coef 但它说 '->' 不是指针。
-
@Jerry:这个任务可能有特殊情况。例如,5x^0 应为 5,-1x^2 应为 -x^2,等等。
-
再看多一点,我也会多分配一点情报:将
read和write成员添加到term,这样一个术语就知道如何读取或写入自身。然后(例如)打印多项式主要是让每个项打印自己。
标签: c++ printing polynomial-math