【发布时间】:2021-01-03 09:24:53
【问题描述】:
我尝试编写一个程序来打印一个数的因数并打印其丰富的因数。但是当我使用它时,我发现了一些问题。如果我在 for 循环内部和 for 循环外部声明一个名为“sum_abundant_factor”的变量,我不知道为什么输出不同。
“sum_abundant_factor”是我用来检查因子是否丰富的变量。 (丰富数是小于其真因数之和的数)。
这是我在 for 循环中声明“sum_abundant_factor”时的代码和输出:
input_number = int(input('Input number : '))
factor = ''
sum_factor = 0
abundant_factor = ''
for i in range(1, input_number+1):
if input_number % i == 0:
sum_abundant_factor = 0
factor += str(i) + ' '
if i < input_number :
sum_factor += i
for j in range(1, i):
if i % j == 0:
sum_abundant_factor += j
if sum_abundant_factor > i:
abundant_factor += str(i) + ' '
print('Factors of {} :'.format(input_number), factor)
print('Abundant Factors :', abundant_factor)
Output :
Input number : 54
Factors of 54 : 1 2 3 6 9 18 27 54
Abundant Factors : 18 54
这是我在 for 循环之前(外部)声明“sum_abundant_factor”时的代码和输出:
input_number = int(input('Input number : '))
factor = ''
sum_factor = 0
abundant_factor = ''
sum_abundant_factor = 0
for i in range(1, input_number+1):
if input_number % i == 0:
factor += str(i) + ' '
if i < input_number:
sum_factor += i
for j in range(1, i):
if i % j == 0:
sum_abundant_factor += j
if sum_abundant_factor > i:
abundant_factor += str(i) + ' '
print('Factors of {} :'.format(input_number), factor)
print('Abundant Factors :', abundant_factor)
Output :
Input number : 54
Factors of 54 : 1 2 3 6 9 18 27 54
Abundant Factors : 6 9 18 27 54
我不知道为什么当我在 for 循环内外声明变量时,丰富的因子输出是不同的。谁能帮我解释一下?
【问题讨论】:
-
对于每个循环,
sum_abundant_factor最初将设置为 0。在循环外部声明后,它将保持其值,并且最初不会为 0。你不断增加它的价值,但在每次运行之前都不会重置。 -
哦,我明白了,谢谢你的解释。