编写一个 Python示例来检查一个数字是不是 Harshad 数字,或者是否使用 while 循环。如果一个数能被给定数的位数之和整除,它就是 Harshad 数。例如,156 可以被 12 整除(1 + 5 + 6),所以它是一个 Harshad 数。
Number = int(input("Enter the Number to Check Harshad Number = "))
Sum = 0
rem = 0
Temp = Number
while Temp > 0:
rem = Temp % 10
Sum = Sum + rem
Temp = Temp // 10
print("The Sum of the Digits = %d" %Sum)
if Number % Sum == 0:
print("\n%d is a Harshad Number." %Number)
else:
print("%d is Not a Harshad Number." %Number)
在这个 Python示例中,我们使用 while 循环来划分数字并计算所有数字的和。接下来,if 条件检查该数是否可被 sum 整除。如果是 Tue,那就是 Harshad 数。
def digitsSum(Number):
Sum = rem = 0
while Number > 0:
rem = Number % 10
Sum = Sum + rem
Number = Number // 10
return Sum
Number = int(input("Enter the Number to Check Harshad Number = "))
Sum = digitsSum(Number)
print("The Sum of the Digits = %d" %Sum)
if Number % Sum == 0:
print("%d is a Harshad Number." %Number)
else:
print("%d is Not a Harshad Number." %Number)
Enter the Number to Check Harshad Number = 481
The Sum of the Digits = 13
481 is a Harshad Number.
Enter the Number to Check Harshad Number = 472
The Sum of the Digits = 13
472 is Not a Harshad Number.
Python示例,用于检查给定的数字是否是 Harshad 数字,是否使用函数。
Sum = 0
def digitsSum(Number):
global Sum
if Number > 0:
rem = Number % 10
Sum = Sum + rem
digitsSum(Number // 10)
return Sum
Number = int(input("Enter the Number to Check Harshad Number = "))
Sum = digitsSum(Number)
if Number % Sum == 0:
print("%d is a Harshad Number." %Number)
else:
print("%d is Not a Harshad Number." %Number)
Enter the Number to Check Harshad Number = 92
92 is Not a Harshad Number.
Enter the Number to Check Harshad Number = 448
448 is a Harshad Number.
标签: Tkinter示例