C#创建控制台程序,打印出所有的“水仙花数”,所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个“水仙花数”,因为153=1³+5³+3³。
分析:利用for循环控制100~999之间的数,每个数分解出个位十位和百位,然后判断立方和是否等于该数本身。
源代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _2_7
{
class Program
{
static void Main(string[] args)
{
int a, b, c;
for (int i = 100; i < 1000; i++)
{
a = i % 10; //分解出个位
b = (i / 10) % 10;//分解出十位
c = i / 100; //分解出百位
if (a * a * a + b * b * b + c * c * c == i)
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
运行结果如图所示: