您的位置:首页 > 编程语言 > C#

C#源代码—编写一个程序求出所有的“水仙花数”。“水仙花数”是指一个3位数,其各位数字的立方和恰好等于该数本身。例如153=1*1*1+5*5*5+3*3*3,所以153是“水仙花数”。

2016-01-17 00:29 645 查看
编写一个程序求出所有的“水仙花数”。“水仙花数”是指一个3位数,其各位数字的立方和恰好等于该数本身。例如153=1*1*1+5*5*5+3*3*3,所以153是“水仙花数”。

本题要求两种方法求解:

用for的三重循环完成。

用for的一重循环完成。

两种方法写在一个程序内,输出时分别说明。

using System;
using System.Collections.Generic;
using System.Text;

namespace _
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("一重循环判断:");
            Console.WriteLine("水仙花数有:");
            int i,j, k, l;
            for (i = 100; i < 1000;i++)
            {
                j = i / 100;
                k = i %100/10;
                l = i % 10;
                int n = j * j * j + k * k * k + l * l * l;
                if (n == i)
                    Console.WriteLine(n);
            }
            Console.WriteLine("三重循环判断:");
            Console.WriteLine("水仙花数有:");
            int q, w, e, r;
            for(q=1;q<=9;q++)
                for(w=0;w<=9;w++)
                    for (e = 0; e <= 9; e++)
                    {
                        int s = q * 100 + w * 10 + e;
                        int t = q * q * q + w * w * w + e * e * e;
                        if (s == t)
                            Console.WriteLine(s);
                    }

        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: