C#创建控制台程序,输入一个非负的整数,将其反向后输出。例如输入24789,变成 98742 输出。
分析:将整数的各个数位逐个位分开,一个一个分别输出。将整数各位数字分开的方法是,通过对 10 进行求余得到个位数输出,然后将整数缩小十倍,再求余,并重复上述过程,分别得到十位、百位、……,直到整数的值变成0为止。
源代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _2_5
{
class Program
{
static void Main(string[] args)
{
Console.Write("输入一个非负的整数:\n");
int n;
n = int.Parse(Console.ReadLine());
Console.Write("反向后输出:");
while (n > 0)
{
Console.Write("{0}",n%10);
n = n / 10;
}
Console.ReadLine();
}
}
}
运行结果如图所示: