【问题标题】:Why does this program double print?为什么这个程序会重复打印?
【发布时间】:2012-10-21 02:21:47
【问题描述】:

我无法隔离问题。该程序应该采用两个整数并将它们转换为科学计数法,然后将它们相乘。然而,它两次打印科学概念。但是,它会打印两次信息。

def convert(s):
    print("You typed " + s)
    n=0
    for c in s:
        n=n+1
        if n==1:
            print("In scientific notation:"+str(c)+'.', end='')
        if n!=1:
            print(str(c),end='')
    print('X 10^'+str(len(s)-1))
    return c

def convert_product(u):
    n=0
    for c in u:
        n=n+1
        if n==1:
            print("Product in scientific notation "+c+'.', end='')
        if n!=1:
            print(c, end='')


def main():
    s=input("Please input your first number\n")
    t=input("Please input your second number\n")
    u=str(int(convert(s))*int(convert(t)))
    convert(s)
    convert(t)
    convert_product(u)
    print('X 10^' + str(len(s)+len(t)-2))
main()

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你在这一行调用 convert :

    u=str(int(convert(s))*int(convert(t)))
    

    你又在数字上调用 convert :

    convert(s)
    convert(t)
    

    并且转换功能正在打印。这样你就有了双重打印。

    【讨论】:

    • +1。当函数具有所谓的副作用时就是这种情况。你应该避免这种情况。返回字符串或一个或多个值,而不是打印。然后调用者可以决定如何处理结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2011-10-28
    • 1970-01-01
    相关资源
    最近更新 更多