多项式导数的C ++程序

阅读 141 收藏 0 点赞 0 评论 0

给定一个包含多项式项的字符串,任务是评估该多项式的导数。

什么是多项式?

多项式有两个词:-“ Poly”表示“许多”,“ nomial”表示“项”,其中包括许多项。多项式表达式是包含变量,系数和指数的表达式,它仅涉及变量的加,乘和减运算。

多项式示例

x2 + x + 1

多项式p(x)= mx ^ n的导数为-

m * n * x ^(n-1)

示例

Input: str = "2x^3 +1x^1 + 3x^2"
   val = 2
Output: 37
Explanation: 6x^2 + 1x^0 + 6x^1
   Putting x = 2
   6*4 + 1 + 6*2 = 24 + 1 + 12 = 37

Input: str = “1x^3”
   val = 2
Output: 12
Explanation: 1 * 3 *x^2
   Putting x = 2
   3 * 4 = 12

我们将用来解决上述问题的方法-

  • 将输入作为字符串和值x

  • 现在遍历字符串并检查数字和变量。

  • 继续添加和遍历字符串,直到找到“ +”。

  • 然后m * n * x ^(n-1)。

  • 返回结果。

算法

Start
Step 1-> In function long long term(string polyterm, long long val)
   Declare and initialize coeffStr = "”
   Declare i
   Loop For i = 0 and polyterm[i] != 'x' and i++
      Call coeffStr.push_back(polyterm[i])
      Set coeff = atol(coeffStr.c_str()
      Declare and initialize powStr = ""
      Loop For i = i + 2 and i != polyterm.size() and i++ powStr.push_back(polyterm[i])
         Set power = atol(powStr.c_str());
   Return coeff * power * pow(val, power - 1)
Step 2-> In function long long value(string& str, int val)
   Set ans = 0
   Call istringstream is(str)
   Declare string polyterm
   Loop While is >> polyterm
      If polyterm == "+” then,
         Continue
      Else
         Set ans = (ans + term(polyterm, val))
   Return ans
Step 3-> In function int main()   Declare and initialize str = "2x^3 + 1x^1 + 3x^2"
   Declare and initialize val = 2
   Print the value received by value(str, val)
Stop

示例

#include
using namespace std;
long long term(string polyterm, long long val) {
   //找到系数
   string coeffStr = "";
   int i;
   for (i = 0; polyterm[i] != 'x'; i++)
      coeffStr.push_back(polyterm[i]);
   long long coeff = atol(coeffStr.c_str());
   //获得幂值
   string powStr = "";
   for (i = i + 2; i != polyterm.size(); i++)
      powStr.push_back(polyterm[i]);
   long long power = atol(powStr.c_str());
   //对于ax ^ n,我们返回a(n-1)x ^(n-1)
   return coeff * power * pow(val, power - 1);
}
long long value(string& str, int val) {
   long long ans = 0;
   //使用istringstream获取令牌中的输入
   istringstream is(str);
   string polyterm;
   while (is >> polyterm) {
      //检查令牌是否等于“ +”,然后
      //继续字符串
      if (polyterm == "+")
         continue;
         //否则找到那个的导数
         //特定术语
      else
         ans = (ans + term(polyterm, val));
   }
   return ans;
}
//主要功能
int main() {
   string str = "2x^3 + 1x^1 + 3x^2";
   int val = 2;
   cout << value(str, val);
   return 0;
}

输出结果

37
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号