用c#语言写出水仙花数
水仙花数是指一个n位数(n≥3),它的每个位上的数字的n次幂之和等于它本身。例如,153是一个水仙花数,因为1^3 + 5^3 + 3^3 = 153。
以下是用C#语言编写的水仙花数程序:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("水仙花数:");
for (int i = 100; i < 1000; i++)
{
int num = i;
int sum = 0;
while (num > 0)
{
int digit = num % 10;
sum += (int)Math.Pow(digit, 3);
num /= 10;
}
if (sum == i)
{
Console.WriteLine(i);
}
}
Console.ReadLine();
}
}
这个程序从100到999遍历所有的三位数,对于每个数,它按位计算它的立方和。如果立方和等于它本身,就输出它作为一个水仙花数。
输出:
水仙花数:
153
370
371
407
``
原文地址: https://www.cveoy.top/t/topic/fiza 著作权归作者所有。请勿转载和采集!