其他分享
首页 > 其他分享> > p005_sum_of_square

p005_sum_of_square

作者:互联网

代码1:

 1 def sum_of_square(n):
 2     result=0
 3     while n>0:
 4         result+=n**2
 5         n-=1
 6     return result
 7 
 8 print("Sum of square (3) is: " ,sum_of_square(3))
 9 print("Sum of square (3.14) is: " ,sum_of_square(3.14))
10 print("Sum of square (9) is: " ,sum_of_square(9))

代码2:

 1 def sum_of_square(n):
 2     result=0
 3    # while n>0:
 4     #    result+=n**2
 5     #    n-=1'''
 6     for i in range(0,n+1):
 7         result+=n**2
 8     return result
 9 
10 print("Sum of square (3) is: " ,sum_of_square(3))
11 print("Sum of square (4) is: " ,sum_of_square(4))
12 print("Sum of square (9) is: " ,sum_of_square(9))

 

效果1:

Sum of square (3) is:  14
Sum of square (3.14) is:  15.7584
Sum of square (9) is:  285

效果2:

Sum of square (3) is:  36
Sum of square (4) is:  80
Sum of square (9) is:  810

  这是因为:n=3,循环0,1,2,3共四次,每次result=3**2,所以是3**2*9=36;4**2*5=80;9**2*10=810

总结:

  1. n-=1意思为:n=n-1.n-=n,意思为:n=n-n;
  2. while里面n可以使float类型,range(0,n+1),这个n必须是整数。

 

标签:p005,square,sum,3.14,result,print,Sum
来源: https://www.cnblogs.com/scholarly/p/15419061.html