python - Armstrong 数字的 Python 程序未正确输出
问题描述
def order(x):
n=0
while(x>0):
n=n+1
x=x/10
return n
def isArmstrong(x):
n=order(x)
print(n)
temp=x
sum1=0
while(temp!=0):
r=temp%10
sum1=sum1+pow(r,n)
temp=temp/10
return (sum1==x)
x=int(input("Enter a number: "))
print(isArmstrong(x))
解决方案
你没有取整数,而是取一些实数来满足你的条件。所以这是你犯的小错误。
我做了一些更正
x/10
-->x//10
temp=temp//10
-->temp=temp//10
def order(x):
n=0
while(x>0):
n=n+1
x=x//10 # <-------- Here
return n
def isArmstrong(x):
n=order(x)
temp=x
sum1=0
while(temp!=0):
r=temp%10
sum1=sum1+pow(r,n)
temp=temp//10 # <----------- Here
return (sum1==x)
x=int(input("Enter a number: "))
print(isArmstrong(x))
结果:
Enter a number: 100
False
Enter a number: 370
True
推荐阅读
- django - 如何将反向字段值添加到 django 序列化程序数据集第 2 部分
- c# - C# 动态多维列表或数组
- javascript - 加载时的窗口调度事件不适用于内联脚本
- javascript - 根据选择标签选项显示内容
- android - 如何将 Firebase Auth 令牌传递给 webView 并在 Android 上注册通知
- javascript - 使用 npm 安装 babylonjs 后“不能在模块外使用 import 语句”
- python - 如何避免在河内塔进行无限次数的操作
- android - 自定义后退按钮 - Android 导航
- javascript - Twilio - 如何为每个电话号码发送带有不同正文的批量短信?
- react-native - React Native 警告:列表中的每个孩子都应该有一个唯一的“键”道具