2016-04-18 51 views
1

所以我對我的作業有疑問。程序計數奇數,然後打印它們

計劃必須做到:

* Asks from user the number of clients (not negative int number) 
    * Uses while and gets total number of flowers 
    * Print final sum to screen. 

我們有這樣的文字: 這是婦女節和花店決定給鮮花的婦女。但事情是,只有奇數才能得到它們。所以第一個得到1,第二個得不到任何東西,第三個得到3,第五個得到5等等。如果插入7,則奇數之和爲16:1 + 3 + 5 + 7 = 16。如果用戶插入8,則和也是16:1 + 3 + 5 + 7 = 16。 奇數可以'比女性的數量還要多。

您必須輸入女性的數量。

我已經做到了這一點:

women = int(input("Insert number of buyers: ")) 
i = 1 
sum = 0 
while i < women: 
    i = i + 2 
    sum = sum + i 
print("Total of flowers is: " + str(women)) 

但它dosent工作,我的大腦是完全沒了主意已:(

最終結果必須是這樣的:

Insert number of buyers: 7 
Total of flowers is : 16 
+0

添加'i'到'sum'您的增量'i'之前。另外,打印'sum'。 –

+2

你爲什麼不檢查'我'是否奇怪? –

+0

我同意Zachi的觀點:您的意圖可能是您從1重複到女性的數量,並且僅爲奇數添加。 (我假設你在這方面已經被教導過「如果」;如果你沒有,那麼更接近你所做的事情會更好。) –

回答

2

有在你的代碼中有三個缺陷:

  • 遞增i遞增sum(指第一夫人被三個花)
  • 使用1個基於指數來算的婦女,但使用了錯誤的循環條件(與women=7循環體不會,如果i==7執行之前,所以它應該是i <= women
  • 不打印的答案(sum),但輸入(women

下面是一個固定的版本:

women = int(input("Insert number of buyers: ")) 
i = 1 
sum = 0 
while i <= women: 
    sum = sum + i 
    i = i + 2 
print("Total of flowers is: " + str(sum)) 
0

與列表理解這樣做:

women = int(input("Insert number of buyers: ")) 
flowers = sum(i for i in range(1, women+1) if i%2 == 1) 
print("Total of flowers is:", flowers) 

或者用range的步驟參數:

women = int(input("Insert number of buyers: ")) 
flowers = sum(range(1, women+1, 2)) 
print("Total of flowers is:", flowers) 

或者用循環也可能是這樣的:

women = int(input("Insert number of buyers: ")) 
flowers = 0 
for i in range(1, women+1): 
    if i%2 == 1: 
     flowers += i 
print("Total of flowers is:", flowers) 

還是看像這樣使用循環和range的步驟參數:

women = int(input("Insert number of buyers: ")) 
flowers = 0 
for i in range(1, women+1, 2): 
    flowers += i 
print("Total of flowers is:", flowers) 

在今後的生產代碼,你會去變體1或2

+0

對於提問者來說,這聽起來像是一個很好的方式來宣傳他從互聯網上獲得了他家庭作業的答案。 –

+0

(我同意,如果你想在提問者的實際代碼中完成作業的計算,當然這會比用'while'循環更好一些。) –

+0

你可以在if使用'step'參數來範圍:'range(1,women + 1,2)' –

0

使用for循環將,我的意見,更簡單。

women = int(input("Insert number of buyers: ")) 
sum = 0 

for i in range(1,women+1): 
    if i%2 != 0: # If i is odd 
     sum += 1 

print("Total of flowers is: " + str(sum)) 

women = int(input("Insert number of buyers: ")) 
sum = sum(i for i in range(1,women+1) if i%2 != 0) 

print("Total of flowers is: " + str(sum)) 
0

你只需修改後的代碼:

women = int(input("Insert number of buyers: ")); 
i = 1; 
sum = i; 
if women%2==0: 
    women=women-1; 
while i < women: 
    i = i + 2; 
    sum = sum + i; 
print("Total of flowers is: " + str(sum)); 
相關問題