在不使用结构的情况下添加多项式的数量

Addition of number of polynomials without using structure

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i, j, n, m, c[20], s = 0;
    int *p[100];

我要求用户输入要加的多项式方程的个数:

    printf("Enter the number of equations to add:\n");
    scanf("%d", &m);

并要求用户输入他计划使用的系数数量

    printf("Enter the maximum coefficient size of largest equation:\n");
    scanf("%d", &n);
    for (j = 1; j <= m; j++) {
        printf("Enter the coefficients of equation number %d:\n", j);
        p[j] = (int*)malloc(n * sizeof(int));
        for (i = n; i > 0; i--)
            scanf("%d", p[j] + i);
        printf("The equation %d becomes as follows:\n", j);
        i = n;
        printf("%dx^%d", *(p[j] + i), i - 1);
        for (i = n - 1; i > 0; i--)
            printf("+%dx^%d", *(p[j] + i), i - 1);
        printf("\n");
    }

代码到这里为止工作正常,但我在添加多项式时遇到问题

    printf("On adding all equations we get:\n");
    for (i = n; i > 0; i--) {
        for (j = 1; j <= m; j++) {
            s = s + (*(p[j] + i));
            c[i] = s;
        }
    }
    i = n;
    printf("%dx^%d", c[i], i - 1);
    for (i = n - 1; i > 0; i--)
        printf("+%dx^%d", c[i], i - 1);
    printf("\n");
    return 0;
}

另外,如果可能的话,我不想使用任何其他方法...我们可以类似地乘以多项式吗?

如果你改变

for(j=1;j<=m;j++){

for(s=0,j=1;j<=m;j++){

如果在不同位置分配的动态内存和垃圾值为零,您的代码会给出正确的输出。

您正在为第 p[j] 个指针分配 n*sizeof(int) 个内存

p[j]=(int*)malloc(n*sizeof(int));
for(i=n;i>0;i--)
    scanf("%d",p[j]+i);

也就是说你可以从p[j]+0访问到p[j]+n-1。如果将某些元素读取到 p[j]+n ,则意味着您正在访问不属于您的内存。 我稍微修改了代码,效果很好

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int i,j,n,m,c[20] = {0},s=0;
    int *p[100];
    printf("Enter the number of equations to add:\n");
    scanf("%d",&m);
    printf("Enter the maximum coefficient size of largest equation:\n");
    scanf("%d",&n);
    for(j=1;j<=m;j++){
        printf("Enter the coefficients of equation number %d:\n",j);
        p[j]=(int*)malloc(n*sizeof(int));
        for(i=n-1;i>=0;i--)
            scanf("%d",p[j]+i);
        printf("The equation %d becomes as follows:\n",j);
        i=n-1;
        printf("%dx^%d",*(p[j]+i),i);
        for(i=n-2;i>=0;i--)
            printf("+%dx^%d",*(p[j]+i),i);
        printf("\n");
    }
    printf("On adding all equations we get:\n");
    for(i=n-1;i>=0;i--){
        for(s=0,j=1;j<=m;j++){
            s=s+(*(p[j]+i));
        c[i]=s;
        }
    }
    i=n-1;
    printf("%dx^%d",c[i],i);
    for(i=n-2;i>=0;i--)
        printf("+%dx^%d",c[i],i);
    printf("\n");
    return 0;
}

注意:不要忘记添加对 scanf 和 malloc 的检查。