编写程序,由键盘输入一个三位整数,判断它是不是水仙花数
时间: 2024-05-29 13:12:23 浏览: 13
水仙花数是指一个三位数,它的各位数字的立方和等于它本身。例如:153 = 1^3 + 5^3 + 3^3。
以下是Python代码实现:
num = int(input("请输入一个三位整数:"))
# 分离出百位、十位、个位
hundreds = num // 100
tens = (num % 100) // 10
ones = num % 10
# 判断是否为水仙花数
if num == hundreds ** 3 + tens ** 3 + ones ** 3:
print(num, "是水仙花数")
else:
print(num, "不是水仙花数")
相关问题
编写C语言程序,从键盘输入任意一个3位正整数,判断是否"水仙花数"
水仙花数是指一个三位数的各位数字的立方和等于该数本身,例如153就是一个水仙花数,因为1的立方+5的立方+3的立方等于153。
以下是实现该功能的C语言程序:
```c
#include <stdio.h>
int main() {
int num, digit1, digit2, digit3;
printf("请输入一个三位正整数:");
scanf("%d", &num);
digit1 = num / 100; // 获取百位数字
digit2 = num / 10 % 10; // 获取十位数字
digit3 = num % 10; // 获取个位数字
if (num == digit1*digit1*digit1 + digit2*digit2*digit2 + digit3*digit3*digit3) {
printf("%d是水仙花数\n", num);
} else {
printf("%d不是水仙花数\n", num);
}
return 0;
}
```
程序首先从键盘输入一个三位正整数,然后将其各位数字分别提取出来。通过计算各位数字的立方和,判断该数是否为水仙花数,并输出相应的结果。
使用vb语言编写一个程序其功能是从键盘上输入一个整数,然后判断他是否是水仙
水仙花数是指一个三位数,其各个位上的数字的立方和等于其本身的数。
首先,我们可以使用VB语言编写一个程序来实现从键盘上输入一个整数的功能:
```
Dim num As Integer
num = InputBox("请输入一个整数:")
```
然后,我们可以编写一个函数来判断这个数是否为水仙花数:
```
Function IsNarcissistic(num As Integer) As Boolean
Dim units As Integer
Dim tens As Integer
Dim hundreds As Integer
units = num Mod 10 ' 获取个位数
tens = (num \ 10) Mod 10 ' 获取十位数
hundreds = num \ 100 ' 获取百位数
If (units ^ 3 + tens ^ 3 + hundreds ^ 3) = num Then
IsNarcissistic = True
Else
IsNarcissistic = False
End If
End Function
```
最后,我们可以在程序中调用这个判断函数,并根据返回值输出结果:
```
If IsNarcissistic(num) Then
MsgBox("是水仙花数!")
Else
MsgBox("不是水仙花数!")
End If
```
整合以上代码,我们就可以实现一个判断输入整数是否为水仙花数的程序。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)