为什么在计算';二进制数的补数是多少? 我编写了一个C++代码,用双链表存储二进制数,其中LSB被存储在头节点中。
每当我在head节点中输入“0”时,我在计算1的补码时会出现分段错误,但是当我在head节点中输入“1”时,我没有这个问题 我的代码:为什么在计算';二进制数的补数是多少? 我编写了一个C++代码,用双链表存储二进制数,其中LSB被存储在头节点中。,c++,C++,每当我在head节点中输入“0”时,我在计算1的补码时会出现分段错误,但是当我在head节点中输入“1”时,我没有这个问题 我的代码: #include<iostream> using namespace std; class node { int bin; node *prev,*next; public: node(int b) { bin=b; prev=NULL; next=NULL; } friend class II; }; cl
#include<iostream>
using namespace std;
class node
{
int bin;
node *prev,*next;
public:
node(int b)
{
bin=b;
prev=NULL;
next=NULL;
}
friend class II;
};
class II
{
node *head,*tail;
int digits;
public:
II()
{
head=NULL;
tail=NULL;
}
void dig()
{
cout<<"Enter the number of digits: ";
cin>>digits;
if(digits<2)
{
cout<<"Please enter more digits: ";
cin>>digits;
}
else{}
}
void create()
{
int y;
if(head==NULL)
{
node *q;
cout<<"Enter binary digit: ";
cin>>y;
if(y<0||y>1)
{
cout<<"Enter again: ";
cin>>y;
}
q=new node(y);
head=q;
head->next=NULL;
head->prev=NULL;
}
else
{
cout<<"ll created";
}
}
void insert()
{
node* temp=head;
node* q;
int i,y;
i=1;
while(i<digits)
{
cout<<"Enter the next digit";
cin>>y;
if(y<0||y>1)
{
cout<<"Please enter again: ";
cin>>y;
}
else
{
q=new node(y);
temp->next=q;
q->next=NULL;
q->prev=temp;
tail=q;
temp=temp->next;
i++;
}
}
}
void disp()
{
node *temp=tail;
while(temp!=NULL)
{
cout<<temp->bin;
temp=temp->prev;
}
cout<<endl;
}
void neg()
{
node *temp=tail;
while(temp!=NULL)
{
if(temp->bin==0)
{
cout<<"1";
temp=temp->prev;
}
if(temp->bin==1)
{
cout<<"0";
temp=temp->prev;
}
}
cout<<endl;
}
};
int main()
{
II a;
a.dig();
a.create();
a.insert();
a.disp();
a.neg();
return 0;
}
以及:
为什么会发生这种情况?正如内森所说,调试器是程序员的关键工具。逐行浏览程序并寻找问题是成功的关键技能 我使用了一些工具来重现你的问题。”gdb是Linux上的调试器valgrind'是一个Linux工具,它将查找各种错误,包括内存访问错误 Valgrind指向neg函数
void neg()
{
node *temp=tail;
while(temp!=NULL)
{
if(temp->bin==0)
{
cout<<"1";
temp=temp->prev; // likely temp is first node so temp->prev == nullptr
}
// missing an 'else' statement here?
if(temp->bin==1) // crash here accessing a nullptr
{
cout<<"0";
temp=temp->prev;
}
}
cout<<endl;
}
};
void neg()
{
节点*温度=尾部;
while(temp!=NULL)
{
如果(临时->仓位==0)
{
coutprev==nullptr
}
//这里缺少“else”语句?
if(temp->bin==1)//在这里访问nullptr时崩溃
{
coutWelcome to Stack Overflow!听起来您可能需要学习如何使用调试器来逐步完成代码。有了一个好的调试器,您可以逐行执行程序,并查看它偏离预期的位置。如果您要进行任何编程,这是一个必不可少的工具。进一步阅读:
Enter the number of digits: 4
Enter binary digit: 0
Enter the next digit0
Enter the next digit1
Enter the next digit1
1100
Segmentation fault (core dumped)
void neg()
{
node *temp=tail;
while(temp!=NULL)
{
if(temp->bin==0)
{
cout<<"1";
temp=temp->prev; // likely temp is first node so temp->prev == nullptr
}
// missing an 'else' statement here?
if(temp->bin==1) // crash here accessing a nullptr
{
cout<<"0";
temp=temp->prev;
}
}
cout<<endl;
}
};