计算水仙花数的方法可以通过编程实现,以下是几种不同编程语言中的实现方法:
Python实现
```python
for num in range(100, 1000):
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit 3
temp //= 10
if num == sum:
print(num)
```
C语言实现
```c
include
int main() {
int i, a, b, c, size = 0;
while (scanf("%d%d", &start, &end) == 2) {
for (i = start; i <= end; i++) {
a = i / 100;
b = (i % 100) / 10;
c = i % 10;
total = pow(c, 3) + pow(a, 3) + pow(b, 3);
if (total == i) {
if (size == 0)
printf("%d", i);
else
printf(", %d", i);
size++;
}
}
printf("\n");
}
return 0;
}
```
Java实现
```java
public class NarcissisticNumber {
public static void main(String[] args) {
for (int num = 100; num <= 999; num++) {
int sum = 0;
int temp = num;
while (temp > 0) {
int digit = temp % 10;
sum += Math.pow(digit, 3);
temp /= 10;
}
if (num == sum) {
System.out.println(num);
}
}
}
}
```
JavaScript实现
```javascript
for (let num = 100; num <= 999; num++) {
let sum = 0;
let temp = num;
while (temp > 0) {
let digit = temp % 10;
sum += Math.pow(digit, 3);
temp = Math.floor(temp / 10);
}
if (num === sum) {
console.log(num);
}
}
```
C++实现
```cpp
include include int main() { for (int num = 100; num <= 999; num++) { int sum = 0; int temp = num; while (temp > 0) { int digit = temp % 10; sum += std::pow(digit, 3); temp /= 10; } if (num == sum) { std::cout << num << std::endl; } } return 0; } ``` 总结 以上代码示例展示了如何在不同的编程语言中实现水仙花数的计算。主要步骤包括遍历所有三位数,分离每个数字的各个位,计算这些位的立方和,并判断立方和是否等于原数字。通过这些步骤,可以找出所有三位数中的水仙花数。