我需要使用 C 将 3 位十进制数转换为二进制数。
我的代码:
#include <stdio.h>
#define TWO 2
int main() {
int dec_num; // demical number
int i = 0; // loop cunter
printf("type in 3 digits number to convert to binary\n");
scanf("%d", &dec_num);
while (++i <= 12) {
if (dec_num % TWO != 0) {
printf("1") ;
} else if (dec_num % TWO == 0) {
printf("0");
} else if (dec_num <= 0) {
break;
}
dec_num / TWO;
}
return 0;
}
问题是在 while
循环结束时数字没有除以 2 我该如何解决?
最佳答案
除法后您没有存储dec_num
的值。
dec_num / TWO; //<--------------------
你的 while 循环条件也是错误的。
while(++i <= 12) //<-------------------
你应该执行除法运算直到数字大于0
根据二进制转十进制的规则,应该倒序打印1和0
。但是在您的代码中,您更改了顺序。为了解决这个问题,我们可以将结果存储在一个数组
中,然后我们可以以倒序
打印结果。
这是你修改后的代码,
#include <stdio.h>
#define TWO 2
int main()
{
int dec_num; // demical number
int i=0; // loop cunter
printf("type in 3 digits number to convert to binary\n");
int flag = scanf("%d",&dec_num); //<-----check the user input
if(flag!=1)
{
printf("Input is not recognized as an integer");
return 0;
}
int size=0;
int array[120] = {0}; //<-------to store the result
while(dec_num > 0){ //<------- while the number is greater than 0
if(dec_num % TWO !=0){
array[i] = 1;
}
else if(dec_num % TWO ==0){
array[i] = 0;
}
size = ++i; //<------- store the size of result
dec_num = dec_num / TWO; //<------- divide and modify the original number
}
for(i=size-1;i>=0;i--) //<------- print in reverse order
printf("%d",array[i]);
return 0;
}
关于将 3 位十进制数转换为二进制数 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52955008/