[英]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.