簡體   English   中英

銷售佣金程序使用while循環。 值未更新

[英]Sales commission program using while loop. Value not updating

我的while循環沒有在我運行程序時更新我的​​新銷售佣金程序。 這是我的程序:

 #this program calculates sales commissions and sums the total of all sales commissions the user has entered

print("Welcom to the program sales commission loop")

keep_going='y'

while keep_going=='y':

    #get a salespersons sales and commission rate
    sales=float(input('Enter the amount of sales'))
    comm_rate=float(input('Enter commission rate'))

    total=0

    #calculate the commission
    commission=sales*comm_rate



    print("commission is",commission)



    keep_going=input('Enter y for yes')

    total=total+commission
    print("Total is",total)

print("You have exited the program. Thet total is",total)

程序的輸出如下:Python 3.5.2(v3.5.2:4def2a2901a5,2016年6月25日,22:01:18)在win32上的[MSC v.1900 32位(Intel)]鍵入“ copyright”,“ credits”或“ license()”以獲取更多信息。

Welcom to the program sales commission loop
Enter the amount of sales899
Enter commission rate.09
commission is 80.91
Enter y for yesy
Total is 80.91
Enter the amount of sales933
Enter commission rate.04
commission is 37.32
Enter y for yesy
Total is 37.32
Enter the amount of sales9909
Enter commission rate.10
commission is 990.9000000000001
Enter y for yesn
Total is 990.9000000000001
You have exited the program. Thet total is 990.9000000000001
>>> 

> Blockquote

我究竟做錯了什么? 我想不明白

每次循環時,您都將total設置為零。 如下所示,將total的初始化移到循環外部。

#this program calculates sales commissions and sums the total of all sales commissions the user has entered

print("Welcom to the program sales commission loop")

keep_going='y'

total=0
while keep_going=='y':

    #get a salespersons sales and commission rate
    sales=float(input('Enter the amount of sales'))
    comm_rate=float(input('Enter commission rate'))

    #calculate the commission
    commission=sales*comm_rate

    print("commission is",commission)

    keep_going=input('Enter y for yes')

    total=total+commission
    print("Total is",total)

print("You have exited the program. Thet total is",total)

問題在於,每次重復循環時,您都要重新初始化“總計”。 您無需初始化變量,但是如果需要,則必須在while循環之外進行。 更正后的代碼將是:

#this program calculates sales commissions and sums the total of all sales commissions the user has entered

print("Welcome to the program sales commission loop")

keep_going='y'
total=0
while keep_going=='y':
    #get a salespersons sales and commission rate
    sales=float(input( 'Enter the amount of sales ' ))
    comm_rate=float(input( 'Enter commission rate ' ))

    #calculate the commission
    comission= sales * comm_rate
    print( "commission is {}".format(comission) )

    keep_going=input('Enter y for yes: ')
    total += comission
    print( "Total is {}".format(total) )

print("You have exited the program. Thet total is",total)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM