C语言实现4位数字素数位追加+1值的代码错误排查
错误原因
- 十位数字计算错误:当前代码的十位计算语句
tensplace = ((userinput-onesplace/10))%10;存在运算符优先级问题,/运算优先级高于-,会先计算onesplace/10,个位数字取值范围为0-9,除以10的结果是0,因此这行代码实际等价于tensplace = userinput%10,和个位数值完全相同。比如输入2345时,你计算得到的十位是5、个位也是5,自然输出结果和预期不符。 - 次要问题:提示语的换行符写为
/n,正确的转义换行符应为\n;各位数字拆分逻辑过于冗余,完全不需要先减去低位再计算,直接用整除+取模的组合即可,更简洁也不容易出错。
正确的数字拆分方式
对于4位正整数,各位拆分可简化为:
- 千位:
userinput / 1000 % 10 - 百位:
userinput / 100 % 10 - 十位:
userinput / 10 % 10 - 个位:
userinput % 10
修正后完整代码
#include <stdio.h> int main() { unsigned int userinput; unsigned int onesplace; unsigned int tensplace; unsigned int hundredsplace; unsigned int thousandsplace; printf("Please enter your number \n"); scanf("%u", &userinput); // 简化各位拆分逻辑 thousandsplace = userinput / 1000 % 10; hundredsplace = userinput / 100 % 10; tensplace = userinput / 10 % 10; onesplace = userinput % 10; printf("%u", thousandsplace); if ((thousandsplace == 2)||(thousandsplace == 3)||(thousandsplace == 5)||(thousandsplace == 7)) { printf("%u", thousandsplace + 1); } printf("%u", hundredsplace); if ((hundredsplace == 2)||(hundredsplace == 3)||(hundredsplace == 5)||(hundredsplace == 7)) { printf("%u", hundredsplace + 1); } printf("%u", tensplace); if ((tensplace == 2)||(tensplace == 3)||(tensplace == 5)||(tensplace == 7)) { printf("%u", tensplace + 1); } printf("%u", onesplace); if ((onesplace == 2)||(onesplace == 3)||(onesplace == 5)||(onesplace == 7)) { printf("%u", onesplace + 1); } return 0; }
修正后输入2345,输出结果为2334456,完全符合需求。
内容的提问来源于stack exchange,提问作者A J
相关产品推荐
相关产品推荐

