问题描述
所以我有一个多项式,看起来像这样:-4x ^ 0 + x ^ 1 + 4x ^ 3 - 3x ^ 4
我可以通过空格和'+' ^ 0,x ^ 1,4x ^ 3, - ,3x ^ 4
我如何得到带负号的系数:-4, 4,-3
x是将出现的唯一变量,这将始终按顺序出现
我计划将系数存储在数组中,数组索引为指数
so:-4将在索引0处,1将在索引1处,0处在索引2处,4处于索引3处,-3处于索引4处
你需要治疗隐含1(即在x ^ 1中)。我会这样做:
long coeff;
pre>
if(* token =='x')
{
coeff = 1;
}
else
{
char * endptr;
coeff = strtol(token,& endptr,10);
if(* endptr!='x')
{
//坏标记
}
}
So I have a polynomial that looks like this: -4x^0 + x^1 + 4x^3 - 3x^4
I can tokenize this by space and '+' into: -4x^0, x^1, 4x^3, -, 3x^4How could I just get the coefficients with the negative sign: -4, 1, 0, 4, -3
x is the only variable that will appear and this will alway appear in order
im planning on storing the coefficients in an array with the array index being the exponent
so: -4 would be at index 0, 1 would be at index 1, 0 at index 2, 4 at index 3, -3 at index 4解决方案Once you have tokenized to "-4x^0", "x^1", etc. you can use strtol() to convert the textual representation into a number. strtol will automatically stop at the first non-digit character so the 'x' will stop it; strtol will give you a pointer to the character that stoped it, so if you want to be paranoid, you can verify the character is an x.
You will need to treat implicit 1's (i.e. in "x^1" specially). I would do something like this:
long coeff; if (*token == 'x') { coeff = 1; } else { char *endptr; coeff = strtol(token, &endptr, 10); if (*endptr != 'x') { // bad token } }
这篇关于C ++提取多项式系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!