用我的代码,我想得到一个整数的最后两位。但是当我把x设为正数时,它会取前x位,如果是负数,它会去掉前x位。
代码:
number_of_numbers = 1
num = 9
while number_of_numbers <= 100:
done = False
num = num*10
num = num+1
while done == False:
num_last = int(repr(num)[x])
if num_last%14 == 0:
number_of_numbers = number_of_numbers + 1
done = True
else:
num = num + 1
print(num)
提取数字最后两位的更简单的方法是将数字转换为
str
,并对数字的最后两位进行切片。例如:或者,可以通过使用模
%
运算符(更有效地),(要了解更多信息,请检查How does % work in Python?)来实现:样本运行:
为什么不求出数字模100的绝对值?也就是说,使用
提取最后两个数字?
就性能和清晰度而言,这种方法很难被打败。
要获得
num
的最后两位数字,我将使用一行简单的技巧:这会给你一根绳子。 要得到int,只需用int来包装:
相关问题 更多 >
编程相关推荐