我希望a四舍五入到13.95.
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
Run Code Online (Sandbox Code Playgroud)
该round功能不像我预期的那样工作.
当我尝试print在Python中使用语句时,它给了我这个错误:
>>> print "Hello, World!"
File "<stdin>", line 1
print "Hello, World!"
^
SyntaxError: Missing parentheses in call to 'print'
Run Code Online (Sandbox Code Playgroud)
那是什么意思?
我在这段代码的输出中得到了很多小数(华氏温度到摄氏温度转换器).
我的代码目前看起来像这样:
def main():
printC(formeln(typeHere()))
def typeHere():
global Fahrenheit
try:
Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
except ValueError:
print "\nYour insertion was not a digit!"
print "We've put your Fahrenheit value to 50!"
Fahrenheit = 50
return Fahrenheit
def formeln(c):
Celsius = (Fahrenheit - 32.00) * 5.00/9.00
return Celsius
def printC(answer):
answer = str(answer)
print "\nYour Celsius value is " + answer + " C.\n"
main()
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如何使程序围绕小数点后两位的每个答案?
round()函数的文档声明您传递一个数字,并将小数点后的位置传递给round.因此它应该这样做:
n = 5.59
round(n, 1) # 5.6
Run Code Online (Sandbox Code Playgroud)
但是,实际上,良好的旧浮点怪异爬进来,你会得到:
5.5999999999999996
Run Code Online (Sandbox Code Playgroud)
出于UI的目的,我需要显示5.6.我在互联网上搜索并发现一些文档,这取决于我的Python实现.不幸的是,这发生在我的Windows开发机器和我尝试过的每台Linux服务器上.在这里也看到.
没有创建我自己的圆形库,有什么方法可以解决这个问题吗?
if act == "block" and enemy_decision != 2:
percentage_blocked = (enemy_attack - block)/(enemy_attack) * 100
print("You have blocked %s percent of the enemy's attack." % percentage_blocked)
Run Code Online (Sandbox Code Playgroud)
由此我得到诸如 82.113124523242323 之类的数字。我怎样才能把这个百分比四舍五入到第10位,例如82.1。
我想将整数舍入到最接近的0.25十进制值,如下所示:
import math
def x_round(x):
print math.round(x*4)/4
x_round(11.20) ## == 11.25
x_round(11.12) ## == 11.00
x_round(11.37) ## == 11.50
Run Code Online (Sandbox Code Playgroud)
这在Python中给出了以下错误:
Invalid syntax
Run Code Online (Sandbox Code Playgroud) 我想要的是:
if 1700 / 1000 = 1.7 = int(1) # I want this to be True
lst.append("T")
Run Code Online (Sandbox Code Playgroud)
我的原始代码是:
if 1700 / 1000 == int(1) # This is False and I want it to be True
lst.append("T")
Run Code Online (Sandbox Code Playgroud)
if 语句为 False,因为答案是 1.7 而不是 1。我希望这是真的。所以我希望使用 int 将 1.7 向下舍入为 1,以便 if 语句为 True。