gpt4 book ai didi

C - 将二进制转换为十进制的算法 - 不起作用

转载 作者:行者123 更新时间:2023-11-30 16:55:49 25 4
gpt4 key购买 nike

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

int main()
{
char c1,c2,c3,c4,c5;
int x;

scanf(" %c %c %c %c %c",&c1,&c2,&c3,&c4,&c5);

if (c1,c2,c3,c4,c5 !='0' && c1,c2,c3,c4,c5 !='1'){
printf("Not a binary number!");

}

if (c1=='0' && c2,c3,c4,c5=='0' || c2,c3,c4,c5 =='1'){

c5 = c5-48;
c4 = (c4-48)*2;
c3 = (c3-48)*4;
c2 = (c2-48)*8;
c1 = c1-48;

x = c5+c4+c3+c2+c1;
printf("%d",x);
}

return 0;
}

因此,该代码适用于所有数字,除了最后一个 (c5) 字符输入 0(零)时。当发生这种情况时,我得到“不是二进制数!”。我的错误在哪里? :)

我才刚开始接触 C 和编程,所以请善待我,呵呵

最佳答案

首先你不能一次取二进制数字,你有c1到c5,如果用户输入二进制为100怎么办,就不行了。所以尝试这样的事情。试试这个:

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

int main()
{

int val, base = 1,cn, decinum = 0,rest;
int alert = 0;
printf("Please enter a binary number 0's and 1's: ");

scanf("%d",&val);

cn = val; // saving it for printf
while(val > 0){
rest = val % 10;

if(rest == 0 || rest == 1) {
decinum += rest * base;
val /= 10;
base *= 2;

}else{
alert = 1;
break;
}
}


if(alert){
printf("Sorry not a binary number\n");
}else{
printf("binary: %d ist %d",cn,decinum);
}


return 0;
}

Please enter a binary number 0's and 1's: 01120100

output: Sorry not a binary number

Please enter a binary number 0's and 1's: 101

Output: binary: 101 ist 5

从 cpatricio 和 Jonathan 的评论中,您想到的二进制数很大,例如 8 位,最多 20 位

int main()
{

unsigned long val,cn, decinum = 0;
int rest, base = 1;
int alert = 0;
printf("Please enter a binary number 0's and 1's: ");

scanf("%lu",&val);

cn = val; // save it for printf otherwise after the while loop is val = 0

while(val > 0){
rest = val % 10;

if(rest == 0 || rest == 1) {
decinum += rest * base;
val /= 10;
base *= 2;

}else{
alert = 1;
break;
}
}


if(alert){
printf("Sorry not a binary number\n");
}else{
printf("binary: %lu ist %ld",cn,decinum);
}


return 0;
}

probe Output: Please enter a binary number 0's and 1's:010101100001001011000 binary: 010101100001001011000 ist 705112

Output: Please enter a binary number 0's and 1's:0000001001011000 binary: 0000001001011000 ist 600

关于C - 将二进制转换为十进制的算法 - 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40192315/

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