簡體   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