我不是一個C愛好者,我寫這個,勉強,作爲我的任務的一部分。該程序將輸入兩個多項式並添加並顯示它們。我編寫了輸入和顯示模塊,但程序不運行。我的C程序不運行
在Dev-C++
它說我有主要多個定義。
#include<stdio.h>
#include<conio.h>
// This is my implementation to add and multiply
// two polynomials using linked list
// So far, it just inputs and displays the polynomial
struct term {
int exp;
int coef;
struct term *next;
};
struct term* addTerm(struct term *polynomial,int exp,int coef){ // adds a term to polynomial
if(polynomial == NULL){
polynomial = (struct term *)malloc(sizeof(struct term));
polynomial->exp = exp;
polynomial->coef = coef;
}else{
struct term *newTerm = (struct term *)malloc(sizeof(struct term));
newTerm->exp = exp;
newTerm->coef = coef;
polynomial->next = newTerm;
}
return polynomial;
}
void display(struct term *polynomial){ // displays the polynomial
struct term *p = polynomial;
while(p->next != NULL){
printf("+ %dx%d",p->coef,p->exp); p = p->next;
}
}
void main(){ // run it
int i = 5;
int coef = 0;
int exp = 0;
struct term *polynomial = NULL;
while(i++ < 5){
printf("Enter CoEfficient and Exponent for Term %d",i);
scanf("%d %d",&coef,&exp);
polynomial = addTerm(polynomial,exp,coef);
}
display(polynomial);
getch();
}
如何讓它運行?
與它的問題的結果你得到的* only *錯誤?你有兩次在你的項目中有相同的文件嗎?或者每個都具有'main'函數的多個源代碼? –
在整個C程序中只能有一個'main',包括所有'.c'模塊。 'main'是整個程序的入口點。另外,main中的'while'循環將不會執行,因爲'i'已經不是'<5'。也許你是爲了調試目的而做的...... – lurker
你的'display'函數不檢查NULL'polynomial',所以如果'p'本身是'NULL',它會在'p-> next!= NULL'處執行segfault 。 – lurker