
我在 Ubuntu 14.04.4 LTS 中編寫了 C 程式碼並編譯了它。它按預期工作。
我寫的程式碼是
#include <stdio.h>
#include <stdlib.h>
struct poly{
int coe[100];
};
void mul(struct poly *pr, int a, struct poly *p){
struct poly res;
int i;
for(i = 0; i < 100; i++){
res.coe[i] = 0;
int j;
for(j = 0; j <= i; j++){
res.coe[i] += ((*pr).coe[j])*((*(p + a)).coe[i - j]);
}
}
*pr = res;
}
void main(){
struct poly *p;
p = (struct poly *)malloc(100*sizeof(struct poly));
int n;
printf("no. of poly :");
scanf("%d", &n);
int i; int max = 0;
for(i = 0; i < n; i++){
int de;
printf("deg? of %d:", i+1);
scanf("%d", &de); max += de;
int j;
for(j = 0; j <= de; j++){
printf("co-eff of deg %d:", j);
scanf("%d", &p[i].coe[j]);
}
}
struct poly res;
struct poly *pr;
res = p[0];
pr = &res;
int fi;
for(fi = 1; fi < n; fi++){
mul(&res, fi, p);
}
for(i = 0; i < (max + 1); i++){
printf("%d\n", res.coe[i]);
}
}
Windows 中的結果是
C:\Users\Sai\Documents\C++>gcc ac.c -o ac
C:\Users\Sai\Documents\C++>ac
no. of poly :3
deg? of 1:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
deg? of 2:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
deg? of 3:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
1
3
6
85067032
255201082
510403447
-1897503563
C:\Users\Sai\Documents\C++>
ubuntu中的結果是
sai@sai-Inspiron-7548:~$ gcc ac.c -o ac
sai@sai-Inspiron-7548:~$ ./ac
no. of poly :3
deg? of 1:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
deg? of 2:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
deg? of 3:2
co-eff of deg 0:1
co-eff of deg 1:1
co-eff of deg 2:1
1
3
6
7
6
3
1
sai@sai-Inspiron-7548:~$
如何讓這個程式在windows 10中正確運作。
我寫的程式碼有問題嗎?
謝謝。
答案1
雖然這應該發佈在其他地方,但這是解決方案:
始終初始化!
您沒有初始化coe[100]
.struct poly*
在循環中,您只設定了一些條目,但是您的多功能函數也會存取未初始化的條目。
我假設 Linux 上的 gcc 以某種方式透過預設將它們初始化為 0 來解決這個問題,但是標準將未初始化的整數的值定義為未定義。
MinGW 不會為你初始化它,所以當時記憶體中的任何內容都會弄亂你的結果。
free(p);
編輯:當然,您也應該使用!釋放分配的記憶體。
以下是解決方法:
#include <stdio.h>
#include <stdlib.h>
struct poly{
int coe[100];
};
void mul(struct poly *pr, int a, struct poly *p){
struct poly res;
int i;
for(i = 0; i < 100; i++){
res.coe[i] = 0;
int j;
for(j = 0; j <= i; j++){
res.coe[i] += ((*pr).coe[j])*((*(p + a)).coe[i - j]);
}
}
*pr = res;
}
void main(){
struct poly *p;
p = (struct poly *)malloc(100*sizeof(struct poly));
for(int k = 0; k < 100; k++)
for(int l = 0; l < 100; l++)
p[k].coe[l] = 0;
int n;
printf("no. of poly :");
scanf("%d", &n);
int i; int max = 0;
for(i = 0; i < n; i++){
int de;
printf("deg? of %d:", i+1);
scanf("%d", &de); max += de;
int j;
for(j = 0; j <= de; j++){
printf("co-eff of deg %d:", j);
scanf("%d", &p[i].coe[j]);
}
}
struct poly res;
struct poly *pr;
res = p[0];
pr = &res;
int fi;
for(fi = 1; fi < n; fi++){
mul(&res, fi, p);
}
for(i = 0; i < (max + 1); i++){
printf("%d\n", res.coe[i]);
}
free(p);
}