使用int()按照四舍五入的方式取整、闰年、长阶梯、水仙花、任意摸出8个球、最大公约数
# 使用int()按照四舍五入的方式取整
def four_five(var):
""""""
try:
if var.count('.') == 1:
var = float(var)
return int(var + 0.5)
else:
return '您输入的类型不是浮点数类型!'
except Exception as e:
print('错误是:%s' % e)
print(four_five('180.99'))
print(four_five('180'))
print(four_five('-180'))
print(four_five('-180.49'))
print(four_five('-180.49.99'))
print(four_five('abc'))
print(four_five('汉字'))
print(int('2')) # 正确
print(int('2.9')) # 报错,ValueError: invalid literal for int() with base 10: '2.9'
# 求闰年的程序
def is_run():
year = input('请输入一个年份:').strip()
if year.isdigit():
year = int(year)
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print('闰年')
else:
print('非闰年')
else:
print('输入的类型不正确!')
is_run()
# 有一个长阶梯,若每步上2阶,最后剩1阶,若每步上3阶,最后剩2阶,若每步上5阶,最后剩4阶,若每步上6阶,最后剩5阶,只有每步上7阶,最后刚好一阶都不剩
x = 7
i = 1
flag = 0
while i <= 100:
if (x % 2 == 1) and (x % 3 == 2) and (x % 5 == 4) and (x % 6 == 5) and (x % 7 == 0):
flag = 1
else:
x = 7 * (i + 1)
i += 1
if flag == 1:
print('阶梯数是:', x)
else:
print('找不到答案')
# 求出100-999之间的水仙花
for i in range(100, 1000):
x = int(i / 100) # 求出百位数
y = int(i % 100 / 10) # 求出十位数
z = i % 10 # 求出个位数
if x ** 3 + y ** 3 + z ** 3 == i:
print('所有的水仙花数字是: %d' % i)
# 有红、黄、蓝三种颜色的球,其中红球3个,黄球3个,绿球6个。先将这12个球混合放在一个盒子中,从中任意摸出8个球,编程计算摸出球的各种颜色搭配
print('red\tyellow\tgreen')
for red in range(0, 4):
for yellow in range(0, 4):
for green in range(2, 7):
if red + yellow + green == 8:
# 注意,下边不是字符串拼接,因此不用“+”哦~
print(red, '\t', yellow, '\t', green)
# 最大公约数
def gcd(x, y):
while y:
t = x % y
x = y
y = t
return x
print(gcd(4, 6))
print(gcd(4, 7))