如何用C语言编程来找出并打印所有的水仙花数?
时间: 2024-11-05 08:33:42 浏览: 65
在C语言中,水仙花数是指一个三位数,其各位数字立方之和等于该数本身。例如,153就是水仙花数,因为1^3 + 5^3 + 3^3 = 153。以下是编写一个函数来找出并打印所有水仙花数的基本步骤:
```c
#include <stdio.h>
// 函数来检查是否为水仙花数
int is narcissistic(int num) {
int digits[3], sum = 0;
while (num != 0) {
digits[2] = num % 10; // 取个位
num /= 10;
// 计算各位立方然后加总
for (int i = 0; i < 3; i++) {
sum += pow(digits[i], 3);
}
}
// 如果总和等于原数,返回1;否则返回0
return sum == num;
}
// 主函数来查找和打印水仙花数
void print_narcissistic_numbers(int start, int end) {
for (int i = start; i <= end; i++) {
if (is_narcissistic(i)) {
printf("%d ", i); // 打印找到的水仙花数
}
}
printf("\n");
}
int main() {
int start_num = 100; // 我们通常从最小的三位数开始找
int end_num = 999; // 最大的三位数
printf("水仙花数在%d到%d之间:\n", start_num, end_num);
print_narcissistic_numbers(start_num, end_num);
return 0;
}
```
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.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)