gpt4 book ai didi

c - 不使用 * 运算符的乘法

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:22 25 4
gpt4 key购买 nike

我正在尝试将两个数字相乘并且不应使用 * 运算符的代码。我编写了这段代码,但没有给出预期的解决方案。

#include<stdio.h>
#include<stdlib.h>

int main(int ar,char *arg[])
{
long int a;
long int b;

sscanf(arg[1],"%ld",&a);
sscanf(arg[2],"%ld",&b);

long int count=0;
long int temp=b;
long int prod=0;

while(temp>0)
{
count=0;

while(temp/2>0)
{
temp/=2;
count++;
}

prod+=a<<(count);
temp=b-(1<<count);
}

//printf("%ld %d\n",count,1<<count);
printf("%ld\n",prod);
return 0;
}

谁能解释一下代码中的错误?

最佳答案

以这种方式编辑您的 while 循环。

while(temp>0)
{
count=0;
while(temp/2>0)
{
temp/=2;
count++;
}
prod+=a<<(count);
temp=b-(1<<count);
b=temp //<--
}

关于c - 不使用 * 运算符的乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21091684/

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