#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 添加检查。
关于c - 在不使用结构的情况下添加多项式的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51800431/