005:Python的数值类型

笔记

str-->float-->int

测试题

1.我们人类思维是习惯于“四舍五入”法,你有什么办法使得int()按照“四舍五入” 的方式取整吗?
答:

temp = input('请输入数字:')
choicea = float(temp)
choiceb = int(choicea)
if choicea - choiceb >= 0.5:
    print(choiceb + 1)
else:
    print(choiceb)

按照答案改进:
5.4 “四舍五入”结果为:5,int(5.4+0.5) == 5
5.6 “四舍五入”结果为:6,int(5.6+0.5) == 6

2.尝试写代码实现以下截图功能:
此处输入图片的描述
答:

temp = input('请输入一个数:')
temp = int(temp)
i = 1
while temp > 0:
    print(i)
    i += 1
    temp -= 1

3.尝试写代码实现以下截图功能:
此处输入图片的描述
答:

num = int(input("请输入一个整数:"))
while num:
    print(' '*(num-1)+'*'*num)
    num -= 1

4.写一个程序,判断给定年份是否为闰年。
答:

按照答案修改:

temp = input("请输入一个年份:")
while not temp.isdigit():
    temp = input("输入不合法,请输入一个整数:")
year = int(temp)
if year == 0:
    print("%d 不是一个闰年!"%year)
else:
    if year%400 == 0:
        print("%d 是一个闰年!"%year)
    else:
        if year%4 == 0 and year%100 != 0:
            print("%d 是一个闰年!"%year)
        else:
            print("%d 不是一个闰年!"%year)
posted @ 2018-01-23 20:50  superrrrjia  阅读(407)  评论(0编辑  收藏  举报