用C语言水仙花数编写一段代码
时间: 2024-06-04 10:11:40 浏览: 74
#include <stdio.h>
#include <math.h>
int main()
{
int num, sum = 0, temp, digits = 0;
printf("Enter a number: ");
scanf("%d", &num);
temp = num;
// Count number of digits
while (temp > 0) {
temp /= 10;
digits++;
}
temp = num;
// Calculate sum of each digit raised to the power of number of digits
while (temp > 0) {
sum += pow(temp % 10, digits);
temp /= 10;
}
// Check if number is a narcissistic number
if (sum == num) {
printf("%d is a narcissistic number.\n", num);
} else {
printf("%d is not a narcissistic number.\n", num);
}
return 0;
}
相关问题
c语言水仙花数python
以下是一个用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是一个水仙花数,因为1^3 + 5^3 + 3^3 = 153。
c语言水仙花数的知识点
C语言中的水仙花数是指一个n位数,它的每个位上的数字的n次幂之和等于它本身。例如,153是一个水仙花数,因为1^3 + 5^3 + 3^3 = 153。
以下是一个用C语言编写的判断一个数是否为水仙花数的示例代码:
```c
#include <stdio.h>
#include <math.h>
int isArmstrong(int num) {
int originalNum, remainder, result = 0, n = 0;
originalNum = num;
// 计算数字的位数
while (originalNum != 0) {
originalNum /= 10; ++n;
}
originalNum = num;
// 计算每个位上的数字的n次幂之和
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}
// 判断是否为水仙花数
if (result == num)
return 1;
else
return 0;
}
int main() {
int num;
printf("请输入一个整数:");
scanf("%d", &num);
if (isArmstrong(num))
printf("%d 是一个水仙花数。\n", num);
else
printf("%d 不是一个水仙花数。\n", num);
return 0;
}
```
这段代码首先定义了一个函数`isArmstrong`,用于判断一个数是否为水仙花数。然后在`main`函数中,用户输入一个整数,然后调用`isArmstrong`函数进行判断,并输出结果。
阅读全文
相关推荐
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)