Please enter an integer: 1234
Digit: 4
Digit: 3
Digit: 2
Digit: 1
我现在有一个程序可以反向打印一个整数的数字。而不是上面的输出,我想:
Please enter an integer: 1234
Digit: 4
Digit: 3
Digit: 2
Last Digit: 1
我如何实现这一目标? 这是我的代码:
#include <stdio.h>
int main()
{
int input;
printf("Please enter an integer: ");
scanf("%d", &input);
int num = input;
int i = 0;
while(num > 0)
{
int remainder = num % 10;
num = num /10;
i++;
printf("Digit: %d\n", remainder );
}
return 0;
}
如何在循环的最后一项打印其他内容?
答案 0 :(得分:2)
使用
if (num > 0) //Indicates that there are more digits to come
{
printf("Digit: %d\n", remainder );
}
else // Otherwise, it is the last digit
{
printf("Last Digit: %d\n", remainder);
}
而不仅仅是
printf("Last Digit: %d\n", remainder);
答案 1 :(得分:1)
测试以查看while条件是否会失败是一种方法。
while (num > 0) {
int remainder = num % 10;
num = num / 10;
i++;
if (num > 0) {
printf("Digit: %d\n", remainder);
} else {
printf("Last Digit: %d\n", remainder);
}
}
或更改while条件...
while (num > 9) {
int remainder = num % 10;
num = num / 10;
i++;
printf("Digit: %d\n", remainder);
}
printf("Last Digit: %d\n", num);