水仙花数是指一个 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/oac0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录