【发布时间】:2015-12-05 23:43:01
【问题描述】:
例子:
150 blue balls
250 red balls
蓝球的百分比是多少?
150 除以总球数 (400) 等于 38%
如果我设置它
blue_balls = 1.0 * number_of_blue_balls / (number_of_blue_balls + number_of_red_balls) * 100
我仍然得到十进制(浮动)并且它没有四舍五入。 我尝试添加
int(round(float(blue_balls)))
没有运气
我如何让它以四舍五入的整数形式给我答案?没有小数
谢谢
澄清-这是我写的
number_of_blue_balls = int(input('Enter number of blue balls:'))
number_of_red_balls = int(input('Enter number of red balls:'))
blue_balls= 1.0 * number_of_blue_balls / (number_of_blue_balls + number_of_red_balls) * 100
red_balls = 1.0 * number_of_red_balls / (number_of_blue_balls + number_of_red_balls) * 100
int(round(float(blue_balls)))
int(round(float(red_balls)))
print("Percent blue balls:", blue_balls,'%')
print("Percent red balls:", red_balls,'%')
我尝试简化代码并得到相同的答案,我只需要多行将浮点数转换为整数/百分比
1 number_of_blue_balls= int(input('输入蓝色球的数量:'))
2 number_of_red_balls= int(input('输入红球数量:'))
3
4 blue_balls= int(number_of_blue_balls/ (number_of_blue_balls + number_of_red_balls) * 100
5 red_balls= int(number_of_red_balls/ (number_of_blue_balls + number_of_red_balls) * 100
6
7 print("蓝球百分比:", blue_balls)
8 print("红球百分比:", red_balls)
终于明白了!!!当我添加 .5 和 sep='' 时,我得到了我需要的结果
谢谢大家! 1 number_of_blue_balls= int(input('输入蓝球数:'))
2 number_of_red_balls= int(input('输入红球数量:'))
3
4 blue_balls= int(number_of_blue_balls/ (number_of_blue_balls + number_of_red_balls) * 100 + 0.5)
5 red_balls= int(number_of_red_balls/ (number_of_blue_balls + number_of_red_balls) * 100)
6
7 print("蓝球百分比:", blue_balls, "%", sep='')
8 print("红球百分比:", red_balls, "%", sep='')
【问题讨论】:
-
那还是不行。我的答案还在浮动形式这里给你看我具体写了什么
-
确切的输出是什么?
-
我得到的输出如 100.0 % 0.0% 和 37.5 % 62.5 % 有两个问题,小数以及数字和百分号之间的空格
标签: python floating-point int percentage