簡體   English   中英

在C中將十進制轉換為二進制

[英]Converting decimal to binary in C

該代碼給出了錯誤的答案。 如果數字等於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();   
}

停止為此使用浮點計算。 您容易受到浮點數的影響。 當我和我的編譯器運行您的程序,輸出為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();   
}

但我寧願看到二進制文件以字符串而不是整數構建。

您可以使用一種更簡單的方法將十進制轉換為二進制數字系統

#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