编程输出100-1000之间的水仙花数。利用自定义函数sxh(),功能判断一个三位数是否是水仙花数。
时间: 2023-04-17 22:03:24 浏览: 145
水仙花数是指一个三位数,其各位数字的立方和等于该数本身。例如,153是一个水仙花数,因为1³+5³+3³=153。
以下是利用自定义函数sxh()输出100-1000之间的水仙花数的代码:
```python
def sxh(num):
# 计算各位数字的立方和
sum = 0
for i in str(num):
sum += int(i) ** 3
# 判断是否为水仙花数
if sum == num:
return True
else:
return False
# 输出100-1000之间的水仙花数
for i in range(100, 1000):
if sxh(i):
print(i)
```
输出结果为:
```
153
370
371
407
```
相关问题
C语言 编程输出100-1000之间的水仙花数。利用自定义函数sxh(),功能判断一个三位数是否是水仙花数。
好的,以下是 C 语言代码实现:
```c
#include <stdio.h>
// 自定义函数判断是否是水仙花数
int sxh(int num) {
int sum = 0, temp = num;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
if (sum == num) {
return 1;
} else {
return 0;
}
}
int main() {
int i;
printf("100-1000之间的水仙花数有:\n");
for (i = 100; i <= 1000; i++) {
if (sxh(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
```
运行结果:
```
100-1000之间的水仙花数有:
153 370 371 407
```
c语言编程输出100-1000之间的水仙花数。利用自定义函数sxh(),功能判断一个三位数是否是水仙花数。
可以使用以下代码实现:
```c
#include <stdio.h>
int sxh(int n) {
int sum = 0;
int temp = n;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
if (sum == n) {
return 1; // 是水仙花数
} else {
return 0; // 不是水仙花数
}
}
int main() {
for (int i = 100; i <= 1000; i++) {
if (sxh(i)) {
printf("%d ", i);
}
}
return 0;
}
```
首先定义一个自定义函数 `sxh()`,传入一个整数参数 `n`,表示要判断的数字。
在 `sxh()` 函数中,使用 while 循环,取出 n 的个位、十位和百位数字,求它们的立方和。如果和等于 n,说明 n 是水仙花数,返回 1,否则返回 0。
在主函数中,从 100 到 1000 的范围内循环每个数字,调用 `sxh()` 函数判断是否是水仙花数,如果是,就输出该数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)