简体   繁体   English

如何让它准确检测数字中有多少位?

[英]How do I make it detect exactly how many digits are in a number?

I am trying to get my code to show each digit individually on its own line, and it does do that.我试图让我的代码在自己的行上单独显示每个数字,它确实做到了。 However, I am getting an error at the end of it, so I want to detect exactly how many digits are in the number.但是,最后我收到一个错误,所以我想准确检测数字中有多少位。 I am having trouble finding a solution for this that isn't len(), because for this specific program I am not supposed to use it.我很难找到不是 len() 的解决方案,因为对于这个特定的程序,我不应该使用它。

Here's my code:这是我的代码:

number = int(input("Enter a positive integer: "))
number = str(number)
digits = 0
while True:
    print(number[digits])
    digits += 1

You can create a counter and with a while loop should look like:您可以创建一个计数器,使用 while 循环应该如下所示:

num = int(input("enter num"
result = 0

while num > 10:
  num = num // 10
  result += 1

result += 1


print(result)

It throws an error because you are running an infinite while loop.它会引发错误,因为您正在运行无限的 while 循环。 Use for instead.改为使用。

number = int(input("Enter a positive integer: "))
number = str(number)
digits = 0
for i in number:
    print(i)
    digits+=1

You can also use the log10 (logarithm with base 10) function:您还可以使用log10 (以 10 为底的对数)function:

import math
number = int(input("Enter a positive integer: "))
print(1 + int(math.log10(number)))

You can solve your problem just by printing elements of string concatenated with new-line delimiter without attempts to find how many elements in string:您可以通过打印与换行符连接的字符串元素来解决您的问题,而无需尝试查找字符串中有多少元素:

number = input("Enter a positive integer: ")
print('\n'.join(number))

Just enumerate number.只列举数字。

number = int(input("Enter a positive integer: "))
number = str(number)
for n, number in enumerate(number, start=1):
    print(number)
print(f'Total length: {n}')

# Example:
Enter a positive integer: 514
5
1
4
Total length: 3

The problem with your existing code is the while True: line with no breaks.您现有代码的问题是while True:没有中断的行。 One method to get around that would be:一种解决方法是:

digits = 0
while True:
    try:
        print(number[digits])
        digits += 1
    except IndexError:
        break

Although it is preferable to avoid this altogether by using a simpler solution.尽管最好通过使用更简单的解决方案来完全避免这种情况。

The reason you're getting the error is because when the digits acquires the value of the length of the number say l , then number[l] doesn't exist (The indices start from 0)您收到错误的原因是因为当digits获取数字长度的值时说l ,然后number[l]不存在(索引从 0 开始)

number = input("Enter a positive integer: ")) 

# type(number) is <class 'str'> you don't have to convert to int and reconvert to string

# since <class 'str'> implements iterable you could go like this ..

digits = 0 

for digit in number:

     print(digit)  # digit is still a str here

     digits += 1

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

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