繁体   English   中英

Python For 循环作业

[英]Python For Loop Homework

所以这个问题无论如何都不难,只是措辞令人困惑。 我已经尝试了 3 种解决方案,但没有一个是正确的。 我已经付出了我真正的努力,所以我希望其他人可以帮助我。 这是问题:

使用for循环,编写以下程序:所有等于组成给定数字的数字的乘积的两倍的所有两位数字都显示在一列中。”

以下是我迄今为止尝试过的 3 种解决方案:

1.

num = int(input("Enter a two-digit number: "))
digitArr = []

for i in str(num):
    digitArr.append(i)

result = 1

for j in digitArr:
    result = result * int(j)
result = result ** 2 #here

for i in range(10, 100):
    tempDigitArr = []
    for j in str(i):
        tempDigitArr.append(j)
    tempResult = 1
    for k in tempDigitArr:
        tempResult = tempResult * int(k)
    tempResult = tempResult ** 2 #here
    if tempResult == result:
        print(i)
        tempResult = 1
        continue
    else:
        tempResult = 1
        continue
num = int(input("Enter a two-digit number: "))
digitArr = []

for i in str(num):
    digitArr.append(i)

result = 1

for j in digitArr:
    result = result * int(j)
result = result ** 2 #here

for i in range(10, 100):
    tempDigitArr = []
    for j in str(i):
        tempDigitArr.append(j)
    tempResult = 1
    for k in tempDigitArr:
        tempResult = tempResult * int(k)
    tempResult = tempResult ** 2 #here
    if tempResult == result:
        print(i)
        tempResult = 1
        continue
    else:
        tempResult = 1
        continue
num = int(input("Enter a two-digit number: "))
digitArr = []

for i in str(num):
    digitArr.append(i)

result = 1

for j in digitArr:
    result = result * int(j)

for i in range(10, 100):
    tempDigitArr = []
    for j in str(i):
        tempDigitArr.append(j)
    tempResult = 1
    for k in tempDigitArr:
        tempResult = tempResult * int(k)
    if tempResult == result:
        print(i)
        tempResult = 1
        continue
    else:
        tempResult = 1
        continue

是的,如果有人想知道的话; 我的课程正在使用自动检查系统;-;

方法很简单

test = range(10,99)

for num in test:

    prod = 1
    for digit in str(num): prod = prod * int(digit)

    if num == 2*prod:
        print(num)

有趣的事实:只有 36 人符合此要求

IIUC,你想要:

for i in range(10, 100):
    tens, units = divmod(i, 10)
    if tens*units*2 == i:
        print(i)

我没有给你代码(反正其他人已经这样做了)而是解释你的程序有什么问题(我认为):

  • 你说程序是自动分级的,但问题没有说明输入,所以我猜通过期待input你的程序只是永远等待从未提供的输入; 相反,您可能只需要底部的for num in range(10, 100)循环
  • 如果你做两次相同的计算(你不需要,见上面,但如果),你应该使用def定义一个函数,而不是复制代码
  • 该问题询问数字是其数字乘积的两倍,而不是平方,即使用*2 ,而不是**2
  • 并且您应该将该双乘积与数字本身进行比较,而不是与第一个(未要求的)输入数字的乘积
  • 由于您知道这是一个两位数,因此您实际上不必遍历这些数字,而是可以使用 integer(!)-division //和 modulo %直接访问它们

我相信你会通过这些提示得到正确的结果(而不仅仅是复制完整的代码)。

如果我正确理解了要求,则将从用户那里获得给定的数字,并且两位数字必须与其匹配(不是他们自己):

number = int(input("given number: "))

for n in range(10,100):
    d,u = divmod(n,10)
    if d*u*2 == number:
        print(n)

示例运行:

given number: 36
29
36
63
92

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM