【问题标题】:Error in program to display digits of a given integer [duplicate]显示给定整数数字的程序出错[重复]
【发布时间】:2023-02-21 22:20:59
【问题描述】:

我正在用 python 3 编写代码来显示给定数字的位数。代码如下:

count=0.
def fun(n):
     global count_e
         if  n<0 :
             count_e+=1
         else:
             res=fun(N/10)
             count_e+=1
N=int(input())
fun(N)
print (count_e)

我收到缩进错误。我不知道如何进行。

我试图用我的 python 代码解释问题。我期待有建议的回复。

【问题讨论】:

  • 错误说问题出在哪里?
  • 取消缩进你的如果堵塞。你还需要定义count_e.然后你需要考虑负数以及 float 和 int 之间的差异 - 例如,如果n == 12.5?您是否在这里考虑过递归的含义?

标签: python


【解决方案1】:

这可能是您要找的?

count=0.
def fun(n):
    global count_e
    if  n<0:
        count_e+=1
    else:
        res=fun(N/10)
        count_e+=1
N=int(input())
fun(5)
print(count_e)

将 if 语句向内移动到与全局 count_e 相同的缩进

【讨论】:

  • 请避免回答与拼写错误相关的问题。相反,将它们标记为这样,以便它们被关闭。如果您想提供帮助,您可以发表评论指出错字是什么,尽管在这种情况下,问题甚至是一个常见的重复问题,其中有很多答案
【解决方案2】:

你应该避免使用全局。这是您需要的工作功能:

def get_number_of_digits(int_number):
    int_number = abs(int_number)

    number_digits = 1
    while int_number >= 10:
        number_digits += 1
        int_number /= 10

    return number_digits

【讨论】:

  • 这里的问题不是真的如何计算位数。这是如何解决代码中的错误(甚至没有发布......)
猜你喜欢
  • 2013-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
相关资源
最近更新 更多