我正在编写一个程序,计算一个人在一段时间内的工资,如果他或她的工资在第一天是一分钱,第二天是两便士,并且每天继续加倍。 我已经完成了所有的事情,但我必须进入美元,我不知道如何做它浮动只给我.0当我需要.00
感谢
# Ryan Beardall Lab 8-1 10/31/13
#program calculates the amount of money a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day and continues to double each day.
accumulatedPay = []
payPerDay = []
days = []
#User enters days worked to find out ho much money user will have
def numberDays():
global daysWorked
daysWorked = (input("Enter the days worked "))
return daysWorked
def salaryOnDay(daysWorked):
return float((2**(daysWorked-1))/100)
def calculations():
earnings = 0
for i in range (1, daysWorked + 1):
salary = salaryOnDay(i)
currRow = [0, 0, 0]
currRow[0] = i
currRow[1] = salary
earnings += salary
currRow[2] = earnings
days.append(currRow)
#program prints matrix
def main():
numberDays()
calculations()
for el in days:
print el
main()
答案 0 :(得分:3)
试试这个:
for el in days:
print '{:.2f}'.format(el)
This documentation更详细地描述了字符串格式。
如果您使用的Python版本太旧(我认为<&lt; 2.7),请尝试:
print '{0:.2f}'.format(el)
如果你使用的Python版本太旧了(&lt; 2.6,我认为),请尝试:
print "%.2f"%el
答案 1 :(得分:3)
或者您可以使用currency formatting
>>> import locale
>>> locale.setlocale( locale.LC_ALL, '' )
'English_United States.1252'
>>> locale.currency( 188518982.18 )
'$188518982.18'
>>> locale.currency( 188518982.18, grouping=True )
'$188,518,982.18'
(S.Lott提供)
答案 2 :(得分:1)
我正在做同样的问题,只是通过将浮动格式定义为0.01来开始:
def main():
num_input = int(input('How many days do you have? '))
# Accumulate the total
total = 0.01
for day_num in range(num_input):
if day_num == 0:
print("Day: ", day_num, end=' ')
total = total
print("the pennies today are:", total)
day_num += day_num
else:
print("Day: ", day_num + 1, end=' ')
total += 2 * total
print("the pennies today are:", total)
main()
输出:
你有几天? 5
日:0今天的便士是:0.01
日:2今天的便士是:0.03
日:3今天的便士是:0.09
日:4今天的便士是:0.27
第五天:今天的便士是:0.81
答案 3 :(得分:1)
我是这样做的
P = 0.01
ttlP = P
dys = int(input('How many days would you like to calculate?'))
for counter in range(1, dys + 1):
print('Day',counter,'\t \t \t $',P)
P = P * 2
ttlP = ttlP + P
ttlP = ttlP - P
print('Total pay is $',format((ttlP),'.2f'),sep='')
答案 4 :(得分:-1)
为C#重做此示例。只需使用visual studio中的默认控制台应用程序设置即可开始使用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HW_1_Penny_Doubling
{
class Program
{
static void Main(string[] args)
{
double total = 0.01;
Console.WriteLine("How many completed days will you be working?");
int days = int.Parse(Console.ReadLine());
if(days <= 200)
{
for(int i = 1; i <= days; i++)
{
if (days == 0)
{
Console.WriteLine("At zero days, you won't even make a penny");
}
else
{
Console.WriteLine("Day: " + i);
total = total + (2 * total); // Take the total and add double that to the original amount
Console.WriteLine("Today's total is: " + total);
}
}
}
else
{
Console.WriteLine("The value will be too high, Try a number below 200");
}
}
}
}