c#while实现:输出所有三位数中的水仙花数(水仙花数是三位数,该三位数的个位、十位、百位的立方和等于这个数。例如153=1的立方+5的立方+3的立方)
时间: 2024-03-21 19:43:58 浏览: 31
好的,这是一个简单的问题。可以使用 C# 的 while 循环语句和条件语句实现。代码如下所示:
```csharp
int num = 100;
while (num < 1000)
{
int i = num / 100; // 获取百位数
int j = (num / 10) % 10; // 获取十位数
int k = num % 10; // 获取个位数
if (num == i * i * i + j * j * j + k * k * k)
{
Console.WriteLine(num); // 输出水仙花数
}
num++;
}
```
这段代码中,我们定义了一个变量 `num`,并赋值为 100,表示从 100 开始遍历所有的三位数。然后使用 while 循环语句,当 `num` 不超过 999 时,执行循环体内的代码。
在循环体内,我们使用数学方法获取了 `num` 的百位数、十位数和个位数,并根据水仙花数的定义进行判断。如果 `num` 是水仙花数,则输出它。最后,将 `num` 自增 1,继续下一个循环,直到遍历完所有的三位数。
希望这个回答能够解决你的问题。
相关问题
求三位数的水仙花数c#
以下是一个求解三位数水仙花数的C#代码实现:
```csharp
List<int> narcissisticNumbers = new List<int>();
for (int i = 100; i < 1000; i++)
{
int sum = 0;
int temp = i;
while (temp > 0)
{
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
if (sum == i)
{
narcissisticNumbers.Add(i);
}
}
foreach (int num in narcissisticNumbers)
{
Console.WriteLine(num);
}
```
该代码使用了一个for循环来遍历所有的三位数,然后使用while循环来计算每个数的各位数字的立方和。如果计算结果等于该数本身,则将该数添加到一个列表中。最后,使用foreach循环遍历列表并输出所有的水仙花数。
用CSharp实现:使用枚举器实现输出N以内所有的水仙花数
好的,以下是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;
}
}
}
}
}
```
请确认是否满意,还有其他问题要问吗?