How to use format in python3 to convert variables (floating point numbers) into integers and print them out
天蓬老师
天蓬老师 2017-06-12 09:19:38
0
1
1467
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'N个数字的平均值'

N = 3
sum = 0
count = 0

while count < N:
    num = float(input('number:'))
    sum = num + sum
    count += 1
average = sum / N
print(type(sum))

print("N: %s, sum: %d ,average: %.2f" % (N, sum, average))
print("N:{}, sum:{} ,average:{:.2f}".format(N, sum, average))
# print("N:{}, sum:{:d} ,average:{:.2f}".format(N, sum, average))

The last commented out line reported an error, ValueError: Unknown format code 'b' for object of type 'float'
I want to output sum, such as a floating point number such as 60.0, as an integer

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
漂亮男人

Try this

print("N:{}, sum:{:.0f} ,average:{:.2f}".format(N, sum, average))
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!