python - Python总是四舍五入?
问题描述
我正在尝试完成一项作业,并且非常接近 python 总是将我的答案四舍五入而不是在应该的时候向上取整。这是我的代码:
startingValue = int(input())
RATE = float(input()) /100
TARGET = int(input())
currentValue = startingValue
years = 1
print("Year 0:",'$%s'%(str(int(startingValue)).strip() ))
while years <= TARGET :
interest = currentValue * RATE
currentValue += interest
print ("Year %s:"%(str(years)),'$%s'%(str(int(currentValue)).strip()))
years += 1
这是我的代码输出: 第 0 年:$10000,第 1 年:$10500,第 2 年:$11025,第 3 年:$11576,第 4 年:$12155, 第 5 年:$12762, 第 6 年:$13400,第 7 年:$14071, 第 8 年: 14774 美元, 第 9 年:15513 美元,
以下是应该输出的内容: 第 0 年:$10000,第 1 年:$10500,第 2 年:$11025,第 3 年:$11576,第 4 年:$12155, 第 5 年:$12763, 第 6 年:$13401,第 7 年:$14071, 第 8 年: $14775 , 第 9 年: $15514 ,
我需要他们匹配,AKA 围捕。有人请帮助我:(
解决方案
在 Python 中,int()
构造函数总是向下取整,例如
>>> int(1.7)
1
https://docs.python.org/2/library/functions.html#int
如果 x 是浮点数,则转换将向零截断。
如果你想总是四舍五入,你需要:
>>> import math
>>> int(math.ceil(1.7))
2
或四舍五入到最接近的:
>>> int(round(1.7))
2
>>> int(round(1.3))
1
(参见https://docs.python.org/2/library/functions.html#round ...这个内置函数返回一个浮点数)
推荐阅读
- graphql - 如何从后端消息队列应用程序触发 GraphQL 订阅
- java - 使用 jGit 将文件推送到远程存储库
- javascript - 发布了一个 npm 包,但安装它只有基本文件
- c++ - 如何使用模板构造函数定义推导指南?
- node.js - React Native - 如何使两个设备在连接到同一网络时相互通信?
- php - 如何为我的联系表创建确认页面?
- ruby - ActiveRecord::StatementInvalid: 找不到表'users' Rails 5 教程
- python - 当我的玩家在pygame中碰撞时如何让我的玩家穿过敌人?
- r - 如何在 R 中将“foreach”和“%dopar%”与“R6”类一起使用?
- sql - 如何通过并发查询确保跨多个相关表的数据一致性