简体   繁体   English

数Python中一个数字的最后一位的顺序

[英]Count the order of the last digit of a number in Python

Hy everybody, I'm trying to write a program with Python that tells me the order of the last digit of a number: for example if the number is 230 then the answer is 1, for 0.104 it is 0.001, for 1.0 it is 0.1 and so on... I've tried to write something but it does strange things for float numbers: it is approximately right for numbers that do not end with 0, and it is wrong for those ending with 0. This is what I wrote:大家好,我正在尝试用 Python 编写一个程序,它告诉我一个数字的最后一位数字的顺序:例如,如果数字是 230,那么答案是 1,对于 0.104,它是 0.001,对于 1.0,它是 0.1等等......我试图写一些东西,但它对浮点数做了一些奇怪的事情:对于不以 0 结尾的数字来说,它几乎是正确的,而对于那些以 0 结尾的数字来说,它是错误的。这就是我写的:

def digit(x):
if (x-int(x))==0:
    return 1
else:
    return 0.1*digit(x*10)

Thanks to anybody who will answer.感谢任何会回答的人。

You could use decimal.Decimal to obtain the amount of decimal places, and compute the order of the last digit as 1e^x , x can be obtained through the exponent attribute of the named tuple returned by decimal.Decimal.as_tuple() :您可以使用decimal.Decimal获取小数位数,并将最后一位数字的顺序计算为1e^xx可以通过decimal.Decimal.as_tuple()返回的命名元组的exponent属性获得:

import decimal

def order_last_digit(d):
    dec = decimal.Decimal(str(d))
    return 10**dec.as_tuple().exponent

order_last_digit(230) #10^0=1
# 1

order_last_digit(0.104) #10^-3
# 0.001

order_last_digit(1.0)
# 0.1

it seems the first part of your code works right so i didn't touch it.看来您的代码的第一部分工作正常,所以我没有碰它。

def digit(x):
  if (x-int(x))==0:
    return 1
  else:
    return '0.'+''.join(['0' for i in str(x).split('.')[1][0:-1]]+['1'])

The OP was having difficulties with floating numbers. OP 在浮点数方面遇到了困难。 Also, answering the question was a bit awkward when they state that另外,当他们 state 时,回答这个问题有点尴尬

if the number is 230 then the answer is 1如果数字是 230 那么答案是 1

and

for 1.0 it is 0.1对于 1.0,它是 0.1

The following programs works for many floating point number inputs:以下程序适用于许多浮点数输入:

import math
for g in [230, 1.0,.104, 1.23, 4.12345]:
    f = g
    sigdif = 0
    while 1:
        f = f - (int(math.ceil(f))-1)
        if f > 0.99999999999:
            break
        if f < 0.00000000001:
            break
        f = 10 * f
        sigdif = sigdif -1
    print(g,sigdif)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM