search

Home  >  Q&A  >  body text

How to use format in python3 to convert variables (floating point numbers) into integers and print them out

#!/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

天蓬老师天蓬老师2726 days ago1482

reply all(1)I'll reply

  • 漂亮男人

    漂亮男人2017-06-12 09:21:38

    Try this

    print("N:{}, sum:{:.0f} ,average:{:.2f}".format(N, sum, average))

    reply
    0
  • Cancelreply