C语言十进制转十六进制函数运行无输出问题排查求助
问题根因分析
- 核心原因是代码存在死循环,所有输出逻辑都在死循环之后无法执行:你测试用的输入是20,第一次循环计算
quotient%16得到余数4,进入temp<10的分支,仅给temp赋值了对应的ASCII码,之后没有任何其他操作,商quotient的值永远保持为20,循环永远不会终止,自然不会执行后续的printf输出语句。 - 逻辑分支范围错误:把余数存储、下标递增、商更新的三个必要操作,错误写到了else分支的大括号内部,只有当余数≥10的时候才会执行这三个操作,余数<10的时候完全跳过,导致循环无法推进。
修复方案
调整else分支的大括号范围,把公共操作放到if-else判断之外,修改后的decimalToHex函数逻辑如下:
void decimalToHex(long int decValue) { long int quotient; int i=1,j,temp; char hexadecimalNumber[100]; quotient = decValue; while(quotient!=0) { temp = quotient % 16; if( temp < 10) temp = temp + 48; else temp = temp + 55; // 以下三行原来被错误包裹在else分支内,现在移到判断外通用执行 hexadecimalNumber[i++]= temp; quotient = quotient / 16; } printf("Equivalent hexadecimal value of decimal number %ld: ",decValue); for(j = i -1 ; j> 0; j--) printf("%c",hexadecimalNumber[j]); printf("\nGoodbye!\n"); }
修改后运行即可正常输出:Equivalent hexadecimal value of decimal number 20: 14
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

