简体   繁体   English

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

[英]Converting decimal to binary in C

The code is giving false answers. 该代码给出了错误的答案。 İf number equals 42, it turns it to 101010. Ok, it is true. 如果数字等于42,它将变为101010。好的,这是事实。 But if number equals 4, it turns it to 99. I didn't find the mistake. 但是,如果数字等于4,它将变为99。我没有发现错误。 How can i fix the code? 我该如何修复代码?

#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();   
}

Stop using floating point calculations for this. 停止为此使用浮点计算。 You are subject to the vagaries of floating point. 您容易受到浮点数的影响。 When I ran your program with my compiler, the output was 100. But I guess your compiler treated the floating point pow differently. 当我和我的编译器运行您的程序,输出为100,但我猜你的编译器处理浮点pow不同。

A simple change to make the code behave, and use integer arithmetic only, would be like this: 一个简单的更改,使代码的行为,并仅使用整数算术,将是这样的:

#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();   
}

But I'd rather see the binary built up in a string rather than an integer. 但我宁愿看到二进制文件以字符串而不是整数构建。

You can use a simpler and easier approach to convert 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;  
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM