gpt4 book ai didi

c - c中的二进制转十进制

转载 作者:太空狗 更新时间:2023-10-29 15:49:07 26 4
gpt4 key购买 nike

我有一个简单的代码可以将二进制数转换为十进制数。在我的编译器中,分解对于小于 1000 的数字工作得很好,超出输出总是相同的 1023。有人有想法吗?

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

// how many power of ten is there in a number
// (I don't use the pow() function to avoid trouble with floating numbers)
int residu(int N)
{
int i=0;
while(N>=1){
N=N/10;
i++;
}
return i;
}

//exponentiating a number a by a number b
int power(int a, int b){
int i;
int res=1;
for (i=0;i<b;i++){res=a*res;}
return res;
}

//converting a number N
int main()
{
int i;

//the number to convert
int N;
scanf("%d",&N);

//the final decimal result
int res=0;
//we decompose N by descending powers of 10, and M is the rest
int M=0;

for(i=0;i<residu(N);i++){
// simple loop to look if there is a power of (residu(N)-1-i) in N,
// if yes we increment the binary decomposition by
// power(2,residu(N)-1-i)
if(M+ power(10,residu(N)-1-i) <= N)
{
M = M+power(10,residu(N)-1-i);
res=power(2,residu(N)-1-i)+res;
}
}
printf("%d\n",res);
}

最佳答案

是的,试试这个:

#include <stdio.h>
int main(void)
{
char bin; int dec = 0;

while (bin != '\n') {
scanf("%c",&bin);
if (bin == '1') dec = dec * 2 + 1;
else if (bin == '0') dec *= 2; }

printf("%d\n", dec);

return 0;

}

关于c - c中的二进制转十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12338584/

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