6: 逆序输出1到4位正整数

6 逆序输出1到4位正整数

作者: Turbo 时间限制: 1S 章节: 分支结构

问题描述 :
输入一个不多于4位的正整数,要求按逆序打印出各个位上的数字,例如原数为23,应输出32;如原数为8000,应输出0008;如原数为1,则输出1。应测试以下情况:输入的数为1位、2位、3位、4位正整数;此外,还应测试以下异常情况:输入负数或0,或输入的数超过4位。

输入说明 :
输入一个整数,可能为0,也可能为负数。

输出说明 :
输入1到4位的正整数时,输出该数的逆序,如果是其它整数,则输出“error!”。输出时,行首与行尾均无空格。

输入范例 :
8000
输出范例 :
0008
代码:

#include <stdio.h>
int main()
{
	int n, st[4] = {0};
	int top = -1,i=0;
	while (scanf("%d", &n) != EOF)
	{
		if (n<=0 || n>9999)
		{
			printf("error!");
		}
		else
		{
			while (n != 0)
			{
				top++;
				st[top] = n % 10;
				n /= 10;
			}
			while (i <= top)
			{
				printf("%d", st[i]);
				i++;
			}
		}
		printf("
");
	}
	return 0;
}
Yesterday is history,tomorrow ismystery,but today is a gift!That why it is called Present!
原文地址:https://www.cnblogs.com/VictorierJwr/p/12242181.html