我必须完成以下任务:
实现两个两位二进制数的写入乘法 而不使用
+
、-
、*
、/
和位运算.逻辑上的 运算符&&
、||
和!
只能应用于逻辑表达式AND 而不是数字本身.数组和循环的使用不是 这里是允许的.同样,通过区分所有 这里不允许装16箱.代码的 struct 应该是这样的: 较大位数的数字很容易实现.
这两个数字是从控制台或通过逐位输入的 从文件重定向(正好是四位数).对于个位数 数字,还必须输入前导零.
为此,使用两个函数
add()
,该函数将两个二进制位相加 不带进位(即返回0或1)和carry()
,这决定了 将两位二进制数相加时进位.可以使用其他功能.输出应使这两个因素相邻 如果没有前导零,则后面跟一个等号,乘积 没有前导零.
我的方法是Booth的二进制数乘法算法.然而,我不知道如何在没有循环的情况下实现这一点.
我有正确的算法吗?
上述算法的代码示例:
#include <stdio.h>
// Function to display a binary number
void displayBinary(int n) {
if (n == 0) {
printf("0");
return;
}
int binary[32];
int i = 0;
while (n > 0) {
binary[i] = n % 2;
n /= 2;
i++;
}
for (i--; i >= 0; i--) {
printf("%d", binary[i]);
}
}
// Function to perform Booth multiplication
int boothMultiplication(int multiplicand, int multiplier) {
int m = multiplicand;
int q = multiplier;
int ac = 0; // Accumulator
int q0 = 0; // Least significant bit of q
int q1 = 0; // Next least significant bit of q
int n = sizeof(int) * 8; // Number of bits in an integer
printf("Step\t\tA\t\tQ\t\tQ(-1)\tQ(0)\tOperation\n");
for (int step = 1; step <= n; step++) {
int q0_q1 = (q0 << 1) | q1;
int operation = 0;
if ((q0_q1 & 0b11) == 0b01) {
ac += m;
operation = 1;
} else if ((q0_q1 & 0b11) == 0b10) {
ac -= m;
operation = -1;
}
if (q & 1) {
q1 = q0;
}
q0 = q & 1;
q >>= 1;
printf("%d\t\t\t", step);
displayBinary(ac);
printf("\t");
displayBinary(q);
printf("\t");
displayBinary(q1);
printf("\t");
displayBinary(q0);
printf("\t");
if (operation == 1) {
printf("Addition (+%d)\n", m);
} else if (operation == -1) {
printf("Subtraction (-%d)\n", m);
} else {
printf("No Operation\n");
}
}
return ac;
}
int main() {
int multiplicand, multiplier;
printf("Enter the multiplicand: ");
scanf("%d", &multiplicand);
printf("Enter the multiplier: ");
scanf("%d", &multiplier);
int product = boothMultiplication(multiplicand, multiplier);
printf("\nResult: %d * %d = %d\n", multiplicand, multiplier, product);
return 0;
}