c - 将 3 位十进制数转换为二进制 (C)
问题描述
我需要使用 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;
}
问题是这个数字在循环结束时没有除以 2我该while
如何解决?
解决方案
您没有存储dec_num
除法后的值。
dec_num / TWO; //<--------------------
您的 while 循环条件也是错误的。
while(++i <= 12) //<-------------------
您应该执行除法运算,直到数字大于 0
根据二进制转十进制的规则,应该在reverse order
. 但是在您的代码中,您更改了顺序。为了解决这个问题,我们可以将结果存储在 an 中array
,然后我们可以将结果打印到reverse order
.
这是您修改后的代码,
#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;
}
推荐阅读
- nodemcu - 如何通过 nrf24l01 发送大于 32 字节的结构
- javascript - Maximo JS 自动化脚本:未定义“importPackage”
- javascript - 如何批量执行 Promise(先解析 10,然后再解析 10,依此类推)
- python - 调用 clear_widgets 时,它不会删除 ScreenManager 中的屏幕
- loops - Vue:避免重复计算
- firebase - 无法确定任务“:app:preDebugBuild”的依赖关系
- ios - 在 UI 测试中找到 UIRefreshControl
- angular - 错误:多个自定义值访问器与未指定名称属性的表单控件匹配
- javascript - 使用 Javascript 使用类名填充元素
- hadoop-yarn - yarn logs 抛出“not valid bcfile”错误