【问题标题】:What does round(value, 2) do?round(value, 2) 有什么作用?
【发布时间】:2015-07-23 23:16:49
【问题描述】:

我目前正在通过 MIT OCW 参加免费的在线课程。我遇到了某个问题,我正在尝试了解解决方案。我不确定“2”在做什么。是 (minMonthlyPaymentRate * balance, 2) 中的两个,解决方法如下:

# 6.00 PS1-A Solution
# Determines remaining credit card balance after a year of making the minimum payment each month

balance = float(raw_input("Enter the outstanding balance on your credit card: "))
annualInterestRate = float(raw_input("Enter the annual credit card interest rate as a decimal: "))
minMonthlyPaymentRate = float(raw_input("Enter the minimum monthly payment rate as a decimal: "))

# Monthly Interest Rate
monthlyInterestRate = annualInterestRate/12

# Initialize state variables
numMonths = 1
totalAmtPaid = 0

while numMonths <= 12:
    # Minimum monthly payment of balance at start of the month
    minPayment = round(minMonthlyPaymentRate * balance,2)**This Two!?**
    totalAmtPaid += minPayment

    # Amt of monthly payment that goes to interest
    interestPaid = round(monthlyInterestRate * balance,2)

    # Amt of principal paid off
    principalPaid = minPayment - interestPaid

    # Subtract monthly payment from outstanding balance
    balance -= principalPaid

    print "Month:", numMonths
    print "Minimum monthly payment:", minPayment
    print "Remaining balance:", balance

    # Count this as a new month     
    numMonths += 1

print "RESULT"
print "Total amount paid:",totalAmtPaid
print "Remaining balance:",balance

【问题讨论】:

  • 查看docs,它四舍五入到位数,在本例中为 2
  • 它只是说结果应该四舍五入到小数点后两位...
  • 好的,谢谢。这是有道理的。
  • 您自己在文档中找不到这个?
  • 你能把例子减少到一行吗?

标签: python rounding


【解决方案1】:

正如python documentation of the function round() 中所见,它声明“四舍五入到小数点后的 ndigits 位”。所以这意味着结果将四舍五入到小数点后两位数。

【讨论】:

    【解决方案2】:

    一张图抵千言。

    【讨论】:

      【解决方案3】:

      round() 四舍五入到给定的位数并返回浮点数。

      示例代码:

      val=2.665
      print(round(val, 2);
      
      output:
      6.67
      

      【讨论】:

        猜你喜欢
        • 2017-05-26
        • 1970-01-01
        • 2018-05-22
        • 1970-01-01
        • 1970-01-01
        • 2012-07-07
        • 1970-01-01
        • 2016-02-27
        • 1970-01-01
        相关资源
        最近更新 更多