[英]C++ extract polynomial coefficients
所以我有一個看起來像這樣的多項式:-4x^0 + x^1 + 4x^3 - 3x^4
我可以通過空格和 '+' 將其標記為:-4x^0、x^1、4x^3、-、3x^4
我怎么能得到帶負號的系數:-4, 1, 0, 4, -3
x 是唯一會出現的變量,它總是按順序出現
我計划將系數存儲在數組中,數組索引為指數
所以:-4 將位於索引 0,1 將位於索引 1,0 位於索引 2,4 位於索引 3,-3 位於索引 4
Start with "-4x^0 + x^1 + 4x^3 - 3x^4"
Split after ^number: "-4x^0", " + x^1", " + 4x^3", " - 3x^4"
Now everything behind an ^ is an exponent, everything before the x is an coefficient
編輯:獲取系數(包括符號)的簡單方法:
Init coefficient with 0, sign with '+'
Go through each character before the x from left to right
If it's a number ('0'..'9'), coefficient = coefficient * 10 + number
If it's '-', set sign to '-'
標記為“-4x^0”、“x^1”等后,您可以使用 strtol() 將文本表示轉換為數字。 strtol 將自動停止在第一個非數字字符處,因此 'x' 將停止它; strtol 會給你一個指向阻止它的字符的指針,所以如果你想變得偏執,你可以驗證這個字符是一個 x。
您將需要處理隱式 1(即特別在“x^1”中)。 我會做這樣的事情:
long coeff;
if (*token == 'x')
{
coeff = 1;
}
else
{
char *endptr;
coeff = strtol(token, &endptr, 10);
if (*endptr != 'x')
{
// bad token
}
}
掃描字符串中的“x”,然后向后存儲系數的每個字符,直到遇到空格。 例如:
for (int i=0; i<s.length(); ++i)
{
if (s[i] == 'x')
{
string c;
for (int j=i-1; j>=0 && s[j]!=' '; --j)
c = s[j] + c;
cout << "coefficient: " << c << endl;
}
}
為了快速解決,我的方法是編寫一個遞歸下降解析器。 在字符串中向前移動並提取所需的組件。 有很多例子可以編寫像這樣的表達式的解析器。
如果你想使用一個庫,你可以使用 boost::regex 或 boost::spirit,這取決於你想采取什么樣的方法。
編寫一個簡單的分詞器。 定義一個數字標記( /[-0123456789][0123456789]+/
),一個指數標記( /x^(::number::)/
)。 忽略空格和+
。
按照您的預期持續讀取標記,直到字符串結束。 然后以您想要的任何形式(例如整數)吐出標記。
int readNumber(const char **input) {
/* Let stdio read it for us. */
int number;
int charsRead;
int itemsRead;
itemsRead = sscanf(**input, "%d%n", &number, &charsRead);
if(itemsRead <= 0) {
// Parse error.
return -1;
}
*input += charsRead;
return number;
}
int readExponent(const char **input) {
if(strncmp("x^", *input, 2) != 0) {
// Parse error.
return -1;
}
*input += 2;
return readNumber(input);
}
/* aka skipWhitespaceAndPlus */
void readToNextToken(const char **input) {
while(**input && (isspace(**input) || **input == '+')) {
++*input;
}
}
void readTerm(const char **input. int &coefficient, int &exponent, bool &success) {
success = false;
readToNextToken(input);
if(!**input) {
return;
}
coefficient = readNumber(input);
readToNextToken(input);
if(!**input) {
// Parse error.
return;
}
exponent = readExponent(input);
success = true;
}
/* Exponent => coefficient. */
std::map<int, int> readPolynomial(const char *input) {
std::map<int, int> ret;
bool success = true;
while(success) {
int coefficient, exponent;
readTerm(&input, coefficient, exponent, success);
if(success) {
ret[exponent] = coefficient;
}
}
return ret;
}
這可能會在具有一些抽象的類中很好地進行(例如,從流而不是純字符串中讀取)。
示例公式:Str = {“-X ^ 10 + 4X ^ 8-3X ^ 2 + 3X ^ 0 = 0”}
void Seperate_Coef_Exp(string str){
bool found=false;
string coef,exp;
int icoef,iexp;
int i=0;
while(1) //Seperating Coefficient
{
coef="";exp="";
if(found==true)
break;
for(;str[i]!='X'&&str[i+1]!='^';i++)
{
coef=coef+str[i];
}
i++; //For X
i++; //For ^
if(coef=="" || coef =="-" || coef =="+" )
coef=coef+"1";
istringstream(coef)>>icoef; //To Convert String to Int
while(1) //Seperating Exponent
{
if(str[i]=='=')
{
found=true;
break;
}
if(str[i]=='+' || str[i]=='-')
break;
exp=exp+str[i];i++;
}
if(exp=="" || exp =="-" || exp=="+")
exp=exp+"1";
istringstream(exp) >>iexp;
cout<<"Coefficient=<<icoef<<" Exp=<<iexp<<endl;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.