用CSharp实现:使用枚举器实现输出N以内所有的水仙花数
时间: 2024-05-08 12:17:57 浏览: 77
好的,以下是C#代码实现:
```
using System;
using System.Collections;
namespace NarcissisticNumber
{
class Program
{
static void Main(string[] args)
{
int n = 500;
var narcissisticNumbers = new NarcissisticNumbers(n);
foreach (var number in narcissisticNumbers)
{
Console.WriteLine(number);
}
}
}
class NarcissisticNumbers : IEnumerable
{
private readonly int _n;
public NarcissisticNumbers(int n)
{
_n = n;
}
public IEnumerator GetEnumerator()
{
for (int i = 1; i < _n; i++)
{
int num = i;
int sum = 0;
while (num > 0)
{
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
if (sum == i)
{
yield return i;
}
}
}
}
}
```
请确认是否满意,还有其他问题要问吗?
阅读全文