判断整数是否为水仙花数
时间: 2023-07-10 09:23:04 浏览: 52
好的,以下是一个简单的 C 语言代码,可以判断输入的整数是否为水仙花数:
```c
#include <stdio.h>
#include <math.h>
int main() {
int num, sum = 0, digit, count = 0, i;
printf("请输入一个三位数:\n");
scanf("%d", &num);
i = num;
while (i > 0) {
count++;
i /= 10;
}
i = num;
while (i > 0) {
digit = i % 10;
sum += (int)pow(digit, count);
i /= 10;
}
if (num == sum) {
printf("%d是水仙花数\n", num);
} else {
printf("%d不是水仙花数\n", num);
}
return 0;
}
```
这个代码中,我们首先从控制台输入一个三位数,然后使用两个 while 循环对这个数进行处理。第一个 while 循环用于计算这个数的位数,第二个 while 循环用于计算这个数的每一位的立方和。最后,我们判断原来输入的数和计算得到的立方和是否相等,如果相等则说明这个数是水仙花数,否则不是。
相关问题
判断一个三为整数是否为水仙花数
水仙花数指一个三位数,其各个数字的立方和等于该数本身。例如,153是一个水仙花数,因为1³ + 5³ + 3³ = 153。
以下是Python代码实现:
```python
num = int(input("请输入一个三位数:"))
# 分离出各个数位
hundreds = num // 100
tens = (num // 10) % 10
units = num % 10
# 判断是否为水仙花数
if num == hundreds**3 + tens**3 + units**3:
print(num, "是水仙花数")
else:
print(num, "不是水仙花数")
```
示例输出:
```
请输入一个三位数:153
153 是水仙花数
```
```
请输入一个三位数:370
370 是水仙花数
```
```
请输入一个三位数:456
456 不是水仙花数
```
python判断一个三为整数是否为水仙花数
水仙花数是指一个三位数各个位上的数字的立方和等于该数本身,例如153就是一个水仙花数,因为1³+5³+3³=153。
以下是Python代码实现判断一个三位整数是否为水仙花数:
```python
num = int(input("请输入一个三位整数:"))
# 获取各个位上的数字
a = num // 100
b = num % 100 // 10
c = num % 10
# 判断是否为水仙花数
if num == a**3 + b**3 + c**3:
print(num, "是水仙花数")
else:
print(num, "不是水仙花数")
```
使用input函数获取用户输入的三位整数,然后将该数分解成百位、十位、个位三个数字,判断它们的立方和是否等于原数,最后输出判断结果。
相关推荐
![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)