首页 > 解决方案 > 如何将数字除以python中任意数组中的每个元素?

问题描述

对 Python 非常陌生,我正试图为我的经理制作一个小费计算器。

计算小费的方式是服务器工作一天的百分比,他们得到小费的百分比。例如,如果服务器 1 当天工作 30% 的时间,他们会收到当天提供的 30% 的提示。

我一直试图弄清楚如何将一个数字(代码中的变量“hourNum”)除以存储服务器工作时间的数组中的每个元素。这将使我获得服务器工作一天的百分比。

使用下面的代码,数学似乎无法正确计算或打印正确。

不幸的是,我在 Stack Overflow 上找不到任何类似的问题。

下面附上源代码,问题出在标题为“计算服务器工作天数百分比”的最后一节中:

#get hours in the day
print('Enter how many hours were worked in the day: ')

hourNum = int(input())

#get tips for the day
print("Enter how much tips were earned (enter to the nearest whole dollar, do not use a dollar sign): ")

tipNum = int(input())


# creating an empty list 
lst = [] 
  

# number of elemetns as input 
serverNum = int(input("Enter number of servers that worked the day : ")) 
  

# iterating till the range 
print("Enter the number of hours each server worked (in order): ")

for i in range(0, serverNum): 
    ele = int(input()) 
  
    lst.append(ele) # adding the element 
      
print("You entered: ", lst) 


#calculate percent of day servers worked
n = 0
for i in range (0,serverNum):
    print (hourNum / lst[0 + n])
    n+1

任何提示或帮助将不胜感激:)

标签: python

解决方案


该表达式hourNum / lst[i]100 * lst[i] / hourNum使该值表示每个服务器工作的工作日中的小时数 (hourNum) 乘以 100,从而得到一个百分比。此外,与其打印最终百分比,不如将它们存储在列表中以便程序记住它们?

#get hours in the day
hourNum = int(input('Enter how many hours were worked in the day: '))

#get tips for the day
tipNum = int(input("Enter how much tips were earned (enter to the nearest whole dollar, do not use a dollar sign): "))

# creating an empty list 
lst = [] 

# number of elemetns as input 
serverNum = int(input("Enter number of servers that worked the day: ")) 
  
# iterating till the range 
print("Enter the number of hours each server worked (in order): ")

for i in range(0, serverNum): 
    ele = int(input()) 
  
    lst.append(ele) # adding the element 
      
print("You entered:", lst) 


#calculate percent of day servers worked
lst_percents = []
for i in range (0,serverNum):
    lst_percents.append(round(100* lst[i] / hourNum))

print("The percent of day the servers worked:", lst_percents)

样本输入和输出:

Enter how many hours were worked in the day: 10
Enter how much tips were earned (enter to the nearest whole dollar, do not use a dollar sign): 100
Enter number of servers that worked the day: 4
Enter the number of hours each server worked (in order): 
1
2
4
5
You entered: [1, 2, 4, 5]
The percent of day the servers worked: [10, 20, 40, 50]

我将把每个服务器的提示计算留给你。希望使用服务器工作天数百分比的列表会更容易。


推荐阅读