在打印多项式时,第一个系数和指数被重复打印n次(无条件)次。
Input:
No of terms: 3
Enter coefficient and exponent: 3 3
Enter coefficient and exponent: 2 2
Enter coefficient and exponent: 1 1
Output:
3x^(3) + 3x^(3) + 3x^(3)
这是代码:
#include<stdio.h>
#include<stdlib.h>
struct Node{
int coef , exp;
struct Node* next;
};
struct Node* create( struct Node* );
int main(){
int val , choice , loc;
struct Node* A = NULL;
struct Node* B = NULL;
A = create( A );
B = create( B );
display( A );
display( B );
do{
printf("\n\n-----POLYNOMIAL OPERATIONS-----\n1.Addition\n2.Multiply\n3.Evaluate\n4.Exit\n--->");
scanf("%d",&choice);
switch( choice ){
case 1://Adding
break;
case 2://Multiplying
break;
case 3://Evaluating
break;
}
}while( choice != 4 );
return 0;
}
struct Node* create( struct Node* p ){
int i , c , x , t;
printf("\nNumber of terms: ");
scanf("%d",&t);
for( i = 0 ; i < t ; i++ ){
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
printf("Enter Coefficient & Exponent: ");
scanf("%d%d",&c,&x);
temp->coef = c;
temp->exp = x;
if( p == NULL ){
p = temp;
temp->next = p;
}else{
struct Node* temp1 = p;
while( temp1->next != p ) temp1 = temp1->next;
temp1->next = temp;
temp->next = p;
}
}
return p;
}
void display( struct Node* p ){
struct Node* temp = p;
printf("\nPOLYNOMIAL: ");
do{
printf("%dx^(%d)",p->coef,p->exp);
temp = temp->next;
if( temp != p ){
printf(" + ");
}
}while( temp != p );
}
答案 0 :(得分:2)
你只需要改变:
do{
printf("%dx^(%d)",temp->coef,temp->exp);
temp = temp->next;
...
现在,每次进行显示循环时,您都会取消引用初始节点!
我想指出的是,由于现在正在编写display()
函数,如果传递NULL指针,则会出现段错误。如果您在0
的任一提示中输入Number of terms:
,就会发生这种情况。