C 语言程序,用于求多项式方程的值


2023 年 10 月 20 日, Learn eTutorial
4741

什么是多项式?

多项式是仅包含变量和系数的表达式。

f(x) = ax2 + bx + c 是一个二次多项式方程

其中,

  • x 是一个单一变量
  • a、b 和 c 是其系数。

对多项式,我们可以进行加、减、乘运算,但不能进行除运算。

几乎所有领域都使用多项式,例如数学、物理等。多项式有多种类型;最常见的类型是二次多项式

为了计算多项式,我们必须知道一个基本理论:'x' 的零次方等于一

如何使用 C 语言中的数组求多项式方程的值?

在这个 C 语言程序中,我们使用数组来保存多项式的值或系数。用户必须输入多项式阶数、'x' 的值和系数。

然后我们必须在 `for 循环` 中使用公式计算多项式之和。

"polySum = polySum * x + a[i];"

之后,我们使用另一个 `for 循环` 按照适当的格式打印多项式,通过检查数组 **a[]** 的值和用户输入的多项式阶数 **N**。

最后,计算多项式之和,并根据 **a[0]** 的值添加运算符,然后显示最终输出。

算法

步骤 1:将头文件导入 C 语言程序以使用内置函数。

步骤 2:定义数组大小和 C 语言程序中使用的其他变量。

步骤 3:从用户那里获取多项式的阶数。

步骤 4:获取多项式方程中未知数 'x' 的值。

步骤 5:使用 `for 循环` 接受系数的值。

步骤 6:Polysum 初始化为数组的第一个元素。

步骤 7:使用一个 `for 循环` 从 1 到项数,每次递增 1,

我们计算 polySum = polySum * x + a[i]

步骤 8:现在将 power = N 赋值,并使用 `for 循环` 打印多项式。

步骤 9:如果 Power 小于零,则 `break` 程序。

步骤 10:如果数组元素大于零,打印符号为 '+',否则如果数组元素

小于零,打印字符为 '-',否则不打印任何内容。

步骤 11:现在使用 C 语言编程中的 `printf` 打印多项式和多项式之和。

C 语言源代码

                                          #include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10

void main()
{
  int a[MAXSIZE];
  int i, N, power;
  float x, polySum;
  printf("Enter the order of the polynomial\n"); /* enter order of polynomial */
  scanf("%d", & N);
  printf("Enter the value of x\n"); /* value of x */
  scanf("%f", & x);

  /*Read the coefficients into an array*/

  printf("Enter %d coefficients\n", N + 1);
  for (i = 0; i <= N; i++) {
    scanf("%d", & a[i]);
  }
  polySum = a[0];
  for (i = 1; i <= N; i++) {
    polySum = polySum * x + a[i]; /* calculating the polysum  */
  }
power = N;
 
    printf("Given polynomial is: \n");
    for (i = 0; i <= N; i++)
    {
        if (power < 0)
        {
            break;
        }
        /*  displaying polynomial  */
        if (a[i] > 0 & i!=0)
            printf(" + ");
        else if (a[i] < 0)
            printf(" - ");
        else
            printf(" ");
        printf("%dx^%d  ", abs(a[i]), power--);
  }
  printf("\nSum of the polynomial = %6.2f\n", polySum); /* displays the sum */
}
                                      

输出

RUN 1

Enter the order of the polynomial
2
Enter the value of x
2
Enter 3 coefficients
3
2
6

Given polynomial is:
 3x^2 + 2x^1 + 6x^0 
Sum of the polynomial =  22.00

RUN 2

Enter the order of the polynomial
4
Enter the value of x
1
Enter 5 coefficients
3
-5
6
8
-9

Given polynomial is:
 3x^4   - 5x^3   + 6x^2   + 8x^1   - 9x^0
Sum of the polynomial =   3.00