0

代码给出了错误的答案。如果数字等于 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();   
}
4

2 回答 2

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

但我宁愿看到二进制文件建立在一个字符串而不是一个整数中。

于 2012-09-30T19:27:47.587 回答
1

您可以使用更简单的方法将十进制转换为二进制数字系统

#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;  
}  
于 2015-08-24T06:39:21.947 回答