【发布时间】:2020-04-12 20:37:04
【问题描述】:
当我使用scanf 输入一个整数并拆分该整数并逐行打印它而不使用数组时,我正在尝试编写一个 c 程序。我可以举例说明我将如何做到这一点。
123 / 100 = 1
123 % 100 = 23
23 / 10 = 2
23 % 19 = 3
1
2
3
我知道该怎么做,但问题是当我运行这段代码时 .
# include <stdio.h>
# include <string.h>
# include <math.h>
int main (void)
{
int no, a;
int count, new;
int newNum = 0;
printf("Enter an intger number = ");
scanf("%d", &no);
newNum = no;
printf("You entered = %d\n", newNum);
while(newNum != 0){
newNum = newNum / 10;
count++;
}
count--;
count = pow(10, count);
printf("Power of ten = %d\n", count);
while(count != 1){
new = no / count;
no = no % count;
printf("%d\n", new);
count = count / 10;
}
return 0;
}
输出:
Enter an intger number = 123
You entered = 123
Power of ten = -2147483648
0
0
0
0
0
0
0
0
-5
-9
Floating point exception (core dumped)
问题是十行的幂没有输出正确的值但是如果我评论第二个while循环部分。
# include <stdio.h>
# include <string.h>
# include <math.h>
int main (void)
{
int no;
int count, new;
int newNum = 0;
printf("Enter an intger number = ");
scanf("%d", &no);
newNum = no;
printf("You entered = %d\n", newNum);
while(newNum != 0){
newNum = newNum / 10;
count++;
}
count--;
count = pow(10, count);
printf("Power of ten = %d\n", count);
// while(count != 1){
// new = no / count;
// no = no % count;
// printf("%d\n", new);
// count = count / 10;
// }
return 0;
}
输出:
Enter an intger number = 123
You entered = 123
Power of ten = 100
这一次十的幂显示正确的值。
我可以做些什么来避免这个问题?
和
- 有什么方法可以在不使用数组的情况下做到这一点?
【问题讨论】:
-
当
count未初始化且具有不确定值时,您执行count++。 -
有什么方法可以在不使用数组的情况下做到这一点...?您没有使用数组...您能详细说明一下吗?
-
为什么要在没有
%的情况下这样做?您到底要达到什么目标,或者您要满足的确切要求是什么?如果您使用递归,您可以在大约 5 行代码中完成(尽管仍然使用%)。 -
如我所说,你可以使用递归。
-
void p(int i) { if (!i) return; p(i/10); printf("%d\n",i%10); }
标签: c loops for-loop while-loop integer-division