2012-10-21 133 views
4

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

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() 

回答

3

要调用转换在这一行:

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

而你再次调用上的数字转换:

convert(s) 
convert(t) 

而且转换功能是打印。因此你有双重打印。

+2

+1。当一个函数具有所谓的*副作用*时就是这种情况。你应该避免这种情况。而不是打印,返回字符串或一个或多个值。然后调用者可以决定如何处理结果。 – pepr