整数的最后两位?Python3

2024-09-28 23:21:06 发布

您现在位置:Python中文网/ 问答频道 /正文

用我的代码,我想得到一个整数的最后两位。但是当我把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)

Tags: of代码falsenumberif整数numint
3条回答

提取数字最后两位的更简单的方法是将数字转换为str,并对数字的最后两位进行切片。例如:

# sample function
def get_last_digits(num, last_digits_count=2):
    return int(str(num)[-last_digits_count:])
    #       ^ convert the number back to `int`

或者,可以通过使用模%运算符(更有效地),(要了解更多信息,请检查How does % work in Python?)来实现:

def get_last_digits(num, last_digits_count=2):
    return abs(num) % (10**last_digits_count)
    #       ^ perform `%` on absolute value to cover `-`ive numbers

样本运行:

>>> get_last_digits(95432)
32
>>> get_last_digits(2)
2
>>> get_last_digits(34644, last_digits_count=4)
4644

为什么不求出数字模100的绝对值?也就是说,使用

 abs(num) % 100 

提取最后两个数字?

就性能和清晰度而言,这种方法很难被打败。

要获得num的最后两位数字,我将使用一行简单的技巧:

str(num)[-2:]

这会给你一根绳子。 要得到int,只需用int来包装:

int(str(num)[-2:])

相关问题 更多 >