你刚刚写了二进制到十进制转换器

时间:2018-03-24 03:03:13

标签: c

我无法让它发挥作用。我明白了......那就是小数的6295636 程序只是将四位二进制转换为十进制解释。我认为我的逻辑是合理的,但我不能告诉

#include <stdio.h>

int result = 0;

int power2 = 8;

char num;

int main(){

    printf("Enter FOUR 1's and/or 0's followed by a '*'.\n");
    scanf("%c", &num);

    while (num != '*'){
        if (num == ' '){
            printf("\n");
        } 
        else if (num == 1){
            result = result + power2;
        }
        power2 = power2 / 2;

        scanf("%c", &num);
    }
    printf("That is %i in decimal", &result);
    return 0;
}

1 个答案:

答案 0 :(得分:-1)

您有两个错误:

else if (num == 1)

您在%c中使用scanf,因此您正在将该值作为字符读取。所以 你必须检查num == '1',因为1 != '1'。有关字符数值的详细信息,请参阅ASCII table

第二个错误是

printf("That is %i in decimal", &result);

在这里你必须传递result,但是你传递的是&result指针 到int&result是变量result的地址。还要添加换行符 到printf

printf("That is %i in decimal\n", result);

此外,没有理由将resultpowernum声明为全球 变量,你为什么这样做?只需在main内声明它们 功能

检查scanf的返回值以查看是否也是一个好主意 成功阅读和转换用户的价值,这使得 程序更健壮。您还应该检查用户是否输入了某些内容 与'1''0'不同。

所以修正后的代码:

#include <stdio.h>

int main(){
    int result = 0;
    int power2 = 8;
    char num;

    printf("Enter FOUR 1's and/or 0's followed by a '*'.\n");
    int ret = scanf("%c", &num);

    if(ret != 1)
    {
        fprintf(stderr, "Could not read from user\n");
        return 1;
    }

    while (num != '*') {
        if (num == ' '){
            printf("\n");
        } else if(num == '1' || num == '0') {
            // num - '0'  would give you either 1 or 0
            result = result + (num - '0') * power2;
            power2 = power2 / 2;
        } else {
            fprintf(stderr, "Invalid input '%c', ignoring\n", num);
        }

        ret = scanf("%c", &num);
        if(ret != 1)
        {
            fprintf(stderr, "Could not read from user\n");
            return 1;
        }
    }

    printf("That is %i in decimal\n", result);
    return 0;
}