在C中将十进制转换为二进制

时间:2012-09-30 19:18:14

标签: c binary decimal

代码给出了错误的答案。 İf数字等于42,它变为101010.好的,这是真的。但如果数字等于4,则将其变为99.我没有发现错误。我该如何修复代码?

#include<stdio.h>
#include<conio.h>
#include<math.h>

int main()
{
    int i,digit,number=4;
    long long bin= 0LL;
    i=0;
    while(number>0)   
    {
          digit=number%2;
          bin+=digit*(int)pow(10,i);
          number/=2;
          i++;
    }
    printf("%d ",bin);
    getch();   
}

2 个答案:

答案 0 :(得分:4)

停止为此使用浮点计算。你受制于浮点的变幻莫测。当我使用编译器运行程序时,输出为100.但我猜你的编译器对浮点pow的处理方式不同。

使代码行为的简单更改,仅使用整数运算,如下所示:

#include<stdio.h>
#include<conio.h>
#include<math.h>

int main()
{
    int digit,number=4;
    long long scale,bin= 0LL;
    scale=1;
    while(number>0)   
    {
          digit=number%2;
          bin+=digit*scale;
          number/=2;
          scale*=10;
    }
    printf("%lld ",bin);
    getch();   
}

但我宁愿看到用字符串而不是整数构建二进制文件。

答案 1 :(得分:1)

您可以使用更简单,更简单的方法来转换decimal to binary number system

#include <stdio.h>  

int main()  
{  
    long long decimal, tempDecimal, binary;  
    int rem, place = 1;  

    binary = 0;  

    /* 
     * Reads decimal number from user 
     */  
    printf("Enter any decimal number: ");  
    scanf("%lld", &decimal);  
    tempDecimal = decimal;  

    /* 
     * Converts the decimal number to binary number 
     */  
    while(tempDecimal!=0)  
    {  
        rem = tempDecimal % 2;  

        binary = (rem * place) + binary;  

        tempDecimal /= 2;  
        place *= 10;  
    }  

    printf("\nDecimal number = %lld\n", decimal);  
    printf("Binary number = %lld", binary);  

    return 0;  
}