c++ - 输入第二个多项式后如何修复分段错误?
问题描述
我想使用链表添加两个多项式。但是在第二个链表中输入第二个多项式后,我遇到了分段错误。
当我尝试打印多项式 1 时,幂本身仍为 1,但不会递增。正在尝试所有可能的错误,所以代码可能有点笨拙。
#include<bits/stdc++.h>
using namespace std;
struct node{
int coef;
int po;
node *next;
}*start1=NULL,*go,*go2,*start2=NULL;
int main()
{
int d1,d2;
cout<<"Enter degree of poly 1 :";
cin>>d1;
cout<<"Enter degree of poly 2 :";
cin>>d2;
int i,c,p;
cout<<"Polynomial 1:" ;
for(i=0;i<=d1;i++)
{ p=1;
cout<<"Enter coeff of po "<<i<<" : " ;
cin>>c;
node *temp=new node;
temp->po=p;
p=p+1;
temp->coef=c;
temp->next=NULL;
go=start1;
if(start1==NULL)
{
start1=temp;
continue;
}
while ((go->next)!=NULL)
{
go=go->next;
}
go->next=temp;
p=p+1;
}
cout<<"Polynomial 2 :";
for(i=0;i<=d2;i++)
{ p=1;
cout<<"Enter coeff of po "<<i<<" :";
cin>>c;
node *temp2=new node;
temp2->po=p;
temp2->coef=c;
temp2->next=NULL;
go2=start2;
if(start2==NULL)
{
start2=temp2;
continue;
}
while ((go2->next)!=NULL)
{
go2=go2->next;
cout<<"kk";
}
go2->next=temp2;
p=p+1;
}
go=start1;
while(go!=NULL)
{
go2=start2;
while(go2->next !=NULL)
{
if((go->po)==(go2->po))
{
go->coef = go->coef + go2->coef;
}
go2=go2->next;
}
go=go->next;
}
go=start1;
cout<<"Resultant Polynomial : ";
for(i=0;i<=d1;i++)
{
cout<<go->coef<<"^"<<i+1<<" + ";
go=go->next;
}
我预计权力会增加,但它保留为 1 并且我遇到了分段错误
解决方案
程序崩溃的原因是这里:
cout << "Resultant Polynomial : ";
for (i = 0; i <= d1; i++)
{
cout << go->coef << "^" << i + 1 << " + ";
go
是一个空指针。这是因为在这个片段之前,你有这个循环:
while (go != NULL)
{ ... }
所以当这个循环结束时,go
是一个空指针,因为循环不会以其他方式结束(否则它不会break
或终止)。您的意思是go
在此循环之后设置为不同的初始值吗?
在不相关的注释上,请阅读为什么我不应该#include <bits/stdc++.h>?为什么是“使用命名空间标准; ” 被认为是不好的做法?
推荐阅读
- python - RandomizedSearchCV 并行:调度作业过多导致 NaN 丢失?
- python - open() - 打开通过 UI 与通过控制台创建的文件
- swift - 是否可以指定带有时区(即 GMT 偏移量)但没有时间的 ISO 日期?
- javascript - 如何分块js数组并在块上应用数学函数?
- javascript - 如何在 DataTable 子行中使用 jQuery 返回 div
- javascript - React setState 在变量初始化之前一直运行
- julia - 在 UBUNTU 16.04 中使用 Julia1.2 安装 MXNet.jl 时出现问题
- ansible - 仅当在 ansible 中满足 x 任务条件时才运行 yz 任务
- php - 在php中将新元素插入多维数组
- angular - 为什么 forkJoin 不适用于观察者?