c - 多项式相乘 : Unexpected output

标签 c arrays for-loop polynomial-math

我基本上尝试使用下面给出的代码来查找 (x+1)^2(输入多项式 1 和 2 的幂为 1 1,P1 的系数为 1 1,P2 的系数为 1 1)。

#include <stdio.h>

int main()
{
    int m,n;

    printf("enter the highest powers of P1 and P2\n");
    scanf("%d%d",&m,&n);          //m= power of P1, n=power of P2

    int a[m],b[n],c[m+n];         //a[m]= coeff of P1, b[n]= coeffof P2

    printf("enter the values\n");



    for(int i=0;i<=m;i++)         //takes coeff of P1 as input
      { printf("a[%d]=\n",i);     //array index are same as the power of x
        scanf("%d",&a[i]);
      }

    for(int i=0;i<=n;i++)         //takes coeff of P2 as input
      { printf("b[%d]=\n",i);     //array index are same as the power of x
        scanf("%d",&b[i]);
      }

    for(int i=0;i<=m+n;i++)       //to initialize array c to zero
      { printf("c[%d]=\n",i);
        scanf("%d",&c[i]);
      }

    for(int k=0;k<=m+n;k++)       //k= power of x in the polynomial= array index  
      {  for(int i=0;i<=k;i++)
          c[k]=c[k]+a[i]*b[k-i];  //for fixed k, summing a[i]*b[k-i]
      }

    for(int i=0;i<=m+n;i++)
       printf("c[%d]=%d\n",i,c[i]);

}

我得到的答案是 2293469x^2 + 2x + 1。请帮忙。

最佳答案

这是一个误解,下面的内容就可以了

int a[m+1], b[n+1], c[m+1+n+1];

有效索引将为 0..m 和 0..n。

正常做法是使用 2 2 和 <m , <n .

a 和 b 中的索引超出范围:

for(int k = 0; k <= m+n; k++)
{
    for(int i = 0; i <= k; i++)
    {
        c[k] = c[k] + a[i] * b[k-i];
    }
}

关于c - 多项式相乘 : Unexpected output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46787581/

相关文章:

c - errno、strerror 和 Linux 系统调用

c++ - 跨平台声音API

c - 如何使用 MPI 并行化点积

c - 阅读搜索算法完成的比较次数

c# - 我如何一次更新我的 GUI 分数?

Objective-c 中的 C++ 矩阵

arrays - 是否有用于eclipse的插件在调试时检查2D数组?

php - 试图在 PHP 中读取 StdClass 对象

php - PDO INSERT 语句在计数器循环内不起作用

php - 如何使用 for 循环遍历 mysql_fetch_array()?