c#水仙花数的判定:3位“水仙花数”是指一个三位整数,其各位数字的3次方和等于该数本身。输入一个三位整数并判断不小于该数的最小水仙花数,并给出判断结果。
时间: 2024-05-01 08:16:01 浏览: 17
以下是使用 C# 编写的解决方案:
```csharp
using System;
class Program {
static void Main(string[] args) {
Console.Write("请输入一个三位整数:");
int n = Convert.ToInt32(Console.ReadLine());
// 找到不小于 n 的最小水仙花数
int i = n;
while (true) {
if (IsNarcissisticNumber(i)) {
Console.WriteLine("{0} 是水仙花数。", i);
break;
}
i++;
}
}
// 判断一个数是否为水仙花数
static bool IsNarcissisticNumber(int n) {
int sum = 0;
int temp = n;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
return sum == n;
}
}
```
示例输出:
```
请输入一个三位整数:123
153 是水仙花数。
```
该程序首先让用户输入一个三位整数,然后使用一个循环来找到不小于该数的最小水仙花数。循环中,每次判断一个数是否为水仙花数,如果是,则输出该数并结束循环。判断一个数是否为水仙花数的方法是将每一位数字的三次方加起来,然后与该数本身比较。