水仙花的程序编程怎么写

时间:2025-01-28 07:19:06 网络游戏

Python

```python

def is_narcissistic_number(num):

将数字转换为字符串以获取位数

num_str = str(num)

计算每个位上的数字的n次幂之和

sum_of_powers = sum(int(digit) len(num_str) for digit in num_str)

判断计算结果是否等于原始数字

return sum_of_powers == num

遍历所有三位数,找出所有水仙花数

narcissistic_numbers = [num for num in range(100, 1000) if is_narcissistic_number(num)]

输出结果

print("所有的三位水仙花数:", narcissistic_numbers)

```

Java

```java

public class NarcissisticNumber {

public static void main(String[] args) {

System.out.println("所有的三位水仙花数:");

for (int i = 100; i <= 999; i++) {

int x = i / 100;

int y = i % 100 / 10;

int z = i % 10;

int s = x * x * x + y * y * y + z * z * z;

if (i == s) {

System.out.println(i);

}

}

}

}

```

C++

```cpp

include

include

bool isNarcissisticNumber(int num) {

int originalNum = num;

int sum = 0;

while (originalNum != 0) {

int remainder = originalNum % 10;

sum += pow(remainder, 3);

originalNum /= 10;

}

return sum == num;

}

int main() {

std::vector narcissisticNumbers;

for (int i = 100; i <= 999; i++) {

if (isNarcissisticNumber(i)) {

narcissisticNumbers.push_back(i);

}

}

std::cout << "所有的三位水仙花数:" << std::endl;

for (int num : narcissisticNumbers) {

std::cout << num << " ";

}

std::cout << std::endl;

return 0;

}

```

JavaScript

```javascript

function isNarcissisticNumber(num) {

const numStr = num.toString();

let sumOfPowers = 0;

for (let i = 0; i < numStr.length; i++) {

sumOfPowers += Math.pow(parseInt(numStr[i]), numStr.length);

}

return sumOfPowers === num;

}

const narcissisticNumbers = [];

for (let i = 100; i <= 999; i++) {

if (isNarcissisticNumber(i)) {

narcissisticNumbers.push(i);

}

}

console.log("所有的三位水仙花数:", narcissisticNumbers);

```

这些程序都遵循相同的逻辑:遍历100到999之间的所有数字,计算每个数字的每位数字的立方和,并判断该和是否等于原始数字。如果是,则该数字是水仙花数,并将其添加到结果列表中。最后,输出所有找到的水仙花数。