整数分解:C语言_翁恺老师
正序分解
思路:
特殊情况:数字末尾有0。
#include<cstdio>
int main()
{
// 计算整数的位数
int mask = 1;
int t = x;
while(t> 9) {
t /= 10;
mask *= 10;
}
do {
int d = x / mask;
printf("%d", d);
if(mask > 9) { // 这里的判断条件应该用mask,而不是x
printf(" ");
}
x %= mask;
mask /= 10;
} while(mask > 0); // 注意循环条件
return 0;
}
逆序分解
思路:
在do while循环中,不断对n取余,得到最右边的各位数,并依次输出。
#include<cstdio>
int main()
{
int x = 12345;
do { // 要用do while循环,防止x的初始状态就是0
int d = x%10;
printf("%d", d);
if(x>9) { // 整数分解的最后一轮一定是个位数
printf(" ");
}
x /= 10;
} while( x>0 );
printf("\n");
return 0;
}