我必須撰寫一個程式,要求用戶輸入限制。然后程式計算連續數的總和 (1 2 3 ...),直到總和至少等于用戶設定的限制。
除了結果之外,它還應該列印出執行的計算。我應該只用一個 while 回圈來做到這一點,沒有串列或 True 條件。
limit = int(input("Limit:"))
base = 0
num = 0
calc = " "
while base < limit:
base = num
num = 1
calc = f" {num}"
print(base)
print(f"The consecutive sum: {calc} = {base}")
因此,例如,如果輸入是 10,則輸出應該是 10,其下方應該是“連續和:1 2 3 4 = 10”。如果輸入為 18,則輸出應為 21,其下方應為“連續和:1 2 3 4 5 6 = 21”。
現在我可以讓它列印最終結果(基數)并讓它列印出計算結果,但它列印出一個整數太多了。如果輸入是 10,當它應該在 5 之前停止時,它會列印出 1 2 3 4 5。
uj5u.com熱心網友回復:
我會避免while回圈并使用它range。您可以使用算術推匯出最后一項的值。
如果最后一項是??,那么總和將為??(?? 1)/2,它必須小于或等于輸入限制。將這個方程分解為 ?? 給定極限,我們得到 ?? 是? √(1 8?limit) ? 1) / 2 ?
那么程式可以是:
limit = int(input("Limit:"))
n = int(((1 8 * limit) ** 0.5 - 1) / 2)
formula = " ".join(map(str, range(1, n 1)))
total = n * (n 1) // 2
print(f"The consecutive sum: {formula} = {total}")
uj5u.com熱心網友回復:
我想到的一種方法是連接每次迭代的值:
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
calculation = 'The consecutive sum: '
while base < limit:
calculation = f"{num} "
base = num
num = 1
print(f"{calculation[:-3]} = {base}")
print(base)
#> Limit:18
## The consecutive sum: 1 2 3 4 5 6 = 21
## 21
另一種方法是在每次迭代中列印值,最后沒有換行(但這里最后有額外的 符號):
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
print('The consecutive sum: ', end='')
while base < limit:
print(f"{num} ", end='')
base = num
num = 1
print(f"= {base}")
print(base)
#> Limit:18
## The consecutive sum: 1 2 3 4 5 6 = 21
## 21
uj5u.com熱心網友回復:
可能有一種更有效的方式來寫這個,但這就是我想到的......
sum = 0
long_output = []
for i in range(limit 1):
sum = i
long_output.append(str(i))
print("The consecutive sum: {} = {}".format(' '.join(long_output), sum))
繼續把東西放在一個串列中,然后加入它們。 i必須強制轉換為str型別,因為 join 僅用于字串
注意:輸出開始于0考慮limit可能為 0(我不知道你的約束是什么,如果有的話)
編輯:根據@Copperfield 的推薦進行更新
uj5u.com熱心網友回復:
這是列印計算的示例
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
msg = ""
while base < limit:
msg = msg str(num) " "
base = num
num = 1
msg = msg[:-1] "=" str(limit)
print(msg)
如果limit = 21然后 msg = "1 2 3 4 5 6=21"
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/392105.html
上一篇:在Python中生成副本串列
下一篇:在VBA中洗掉第i行和下一行
