gpt4 book ai didi

C++程序Booths Algorithm 2s Complement using array

转载 作者:行者123 更新时间:2023-11-28 05:49:39 24 4
gpt4 key购买 nike

我已经包含了我遇到逻辑问题的程序。该程序基于 booth 的算法,我已经放了一个片段。在这个“工作”代码片段中,用户在数组 (a[0]=1 LSB) 的帮助下接受十进制数转换为十进制形式,最后计算数组 b[] 的 2s 补码。 现在,当我运行程序时:

    #include<iostream>
using namespace std;
class booth
{
public:
int n;
int b[3];
int comb[3], q[3]; //b=multiplicand q=multiplier
int bb, qq; //bb and qq store actual decimal no.s
booth()
{
for(int i=0; i<4; i++)
{
b[i]=0; //b array stores multiplicand in binary
q[i]=0; //q array stores multiplier in binary
comb[i]=0; //will store calculated 2s complement in
binary
}
n=4;
bb=0;
qq=0;
}
void acceptMm();
void display();
};

void booth :: acceptMm() //function to accept value from user and
//converting it into binary in the form of
//array and then calculating its 2s complement
{
cout<<"Enter Multiplicand: ";
cin>>bb;
cout<<"Enter Multiplier: ";
cin>>qq;
//decimal to binary
int rem1, rem2, i=0, j=0; //rem1 and rem2 are remainders
while(qq!=0)
{
rem2=qq%2;
qq/=2;
q[i]=rem2;
i++;
}
cout<<q[3]<<q[2]<<q[1]<<q[0]<<endl; // to display binary no.
//again decimal to binary
while(bb!=0)
{
rem1=bb%2;
bb/=2;
b[j]=rem1;
j++;
}
cout<<b[3]<<b[2]<<b[1]<<b[0]<<endl; //to display binary no.
// 2s complement:
int ii=0;
int jj=4; //4 bit binary number
while(b[ii]==0 && jj!=0)
{
comb[ii]=b[ii];
ii++;
jj--;
}
comb[ii]=b[ii];
cout<<b[3]<<b[2]<<b[1]<<b[0]<<endl; //displayed value (problem)
ii++;
jj--;
if(jj==0)
{
return;
}
while(jj!=0)
{
if(b[ii]==0)
{
comb[ii]=1;
ii++;
jj--; }
else
{
comb[ii]=0;
ii++;
jj--;
}
}
}

void booth :: display()
{
cout<<"multiplicand\n";
for(int x=3; x>=0; x--)
{
cout<<b[x]<<" ";
}
cout<<endl;
cout<<"multiplier\n";
for(int j=3; j>(-1); j--)
{
cout<<q[j]<<" ";
}
cout<<endl;
cout<<"compliment of multiplicand\n";
for(int y=3; y>(-1); y--)
{
cout<<comb[y]<<" ";
}
}

int main()
{
booth obj;
cout<<"Booths Algorithm\n";
obj.acceptMm();
obj.display();
return 0;
}

Output

Booths Algorithm
Enter Multiplicand: 5
Enter Multiplier: 4
0100
0101
1101
multiplicand
1 1 0 1
multiplier
0 1 0 0
compliment of multiplicand
0 0 1 1

在输出中,我希望第 6 行为 0101,但得到的是 1101。为什么数组 b[] 的值会发生变化?第 5 行的数组 b[] 的值是正确的,为什么它会改变?根据代码,该值不应该改变,对吗? 我卡住了..请帮忙!!任何建议将不胜感激!!

最佳答案

b、q 和 comb 是 3 个元素的数组,因此 b[3] 是数组溢出(其值未知)。事实上 comb 在 b 之后分配,很可能 b[3] 等于 comb[0]。

关于C++程序Booths Algorithm 2s Complement using array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35523998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com