-2
我想找到兩個二進制數字的總和。我的方法是將各個位存儲在一個數組中,然後打印輸出,該輸出也存儲在比前兩個數組大1的數組中。兩個二進制數的大小也是相同的。所以我寫了下面的代碼,因爲我開始使用C++,所以我使用類編寫它。我只是想知道爲什麼作爲參數傳遞我收到「分段錯誤(核心轉儲)」C++程序中的分段錯誤
#include<iostream>
#include<vector>
using namespace std;
class arrays{
private:
int n;
public:
void input(){
cout<<"Enter the size of arrays ";
cin>>n;
}
void array_creation(vector<int>Z){
long int b;
int a;
cout<<"Enter the binary number ";
cin>>b;
while(b!=0){
a=b%10;
Z.push_back(a);
b=b/10;
}
Z[-1]=0;
}
void output(vector<int>Z){
cout<<"The sum of two binary numbers is ";
for(int a=0;a<n+1;a++)
cin>>Z[a];
}
void logic_set(vector<int>Z,vector<int>Y,vector<int>X){
for(int a=n-1;a>=0;a--){
if(Z[a]==0 && Y[a]==0)
X[a+1]=0;
if(Z[a]==0 && Y[a]==1)
X[a+1]=1;
if(Z[a]==1 && Y[a]==0)
X[a+1]=1;
if(Z[a]==1 && Y[a]==1){
X[a+1]=0;
label:
if(Z[a-1]==0)
Z[a-1]=1;
if(Z[a-1]==1)
Z[a-1]==2;
}
if(Z[a]==2){
X[a+1]==Y[a];
goto label;
}
}
}
};
int main(){
arrays a,b;
vector<int>A;
vector<int>B;
vector<int>C;
a.input();
a.array_creation(A);
b.array_creation(B);
a.logic_set(A,B,C);
a.output(C);
}
這是確切的錯誤,以防萬一 The exact error page
首先,在調試器中運行它,並找出它的確切位置崩潰,甚至可能找出原因。你的代碼中也有未定義的行爲,我無法想象爲什麼你會擁有它。用'-1'索引,爲什麼? –
'Z [-1] = 0;'看起來像一個明顯的問題。 – melpomene
你爲什麼使用'goto'語句? – JonatanE