写一个查找水仙花数的代码
时间: 2023-04-07 15:00:53 浏览: 61
以下是查找水仙花数的 Python 代码:
```python
for num in range(100, 1000):
# 分解出个位、十位、百位
digit1 = num // 100
digit2 = (num // 10) % 10
digit3 = num % 10
# 判断是否为水仙花数
if num == digit1 ** 3 + digit2 ** 3 + digit3 ** 3:
print(num)
```
这段代码会输出所有三位数的水仙花数,即 153、370、371 和 407。
相关问题
帮我写一个可以查找水仙花数的C
程序。
当然可以,以下是代码:
#include <stdio.h>
#include <math.h>
int main()
{
int num, sum, temp;
printf("请输入一个三位数:");
scanf("%d", &num);
temp = num;
sum = ;
while (temp != )
{
sum += pow(temp % 10, 3);
temp /= 10;
}
if (sum == num)
printf("%d 是水仙花数\n", num);
else
printf("%d 不是水仙花数\n", num);
return ;
}
函数调用方式写一个水仙花数
好的,这里是一个用C语言实现的主函数,通过函数调用的方式求100-500之间的所有水仙花数并输出:
```c
#include <stdio.h>
#include <stdbool.h>
bool is_narcissistic_number(int n);
int main() {
// 在100-500范围内查找所有水仙花数
for (int n = 100; n <= 500; n++) {
if (is_narcissistic_number(n)) {
printf("%d\n", n);
}
}
return 0;
}
bool is_narcissistic_number(int n) {
int sum_of_cubes = 0;
int temp = n;
while (temp > 0) {
int digit = temp % 10;
sum_of_cubes += digit * digit * digit;
temp /= 10;
}
return sum_of_cubes == n;
}
```
这个程序中,我们定义了一个`is_narcissistic_number`函数来判断一个数是否是水仙花数,并在主函数中调用它来查找100-500之间的所有水仙花数并输出。
希望这个代码可以帮到你!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)