我需要帮助做一个巨蟒的家庭作业问题。
“假设有一个变量h已经与一个正整数值相关联。编写计算值小于h的完美平方和所需的代码,从1开始。(完美平方是一个整数,如9、16、25、36,它等于另一个整数的平方(在本例中分别为3*3、4*4、5*5、6*6 )。将计算的和与变量q关联。例如,如果h是19,则应将30赋给q,因为小于h的完美平方(从1开始)是:1、4、9、16和30==1+4+9+16。“
到目前为止,我真的很接近做对了,但是它总是比它需要的多做一个数字。例如,输入19,而不是停止于1,4,9,16,它还会增加25。
到目前为止,我的代码如下
h_i=input()
h=int(h_i)
s=0
q=0
total=s**2
while total<=h:
s+=1
total=s**2
q+=total
print(total)
print(q)
发布于 2016-02-07 08:13:41
我将提出一种不同的方法,使用一种更"Pythonic“的方法来理解列表:
>>> highest = 19 # in your case this is h
lst = list (n**2 for n in range(1, highest + 1))
lst
[1, 4, 9, 16]
>>> print '\n'.join(str(p) for p in lst)
1
4
9
16
发布于 2016-02-07 08:15:00
我建议修改你的代码以提高可读性和间距。此外,您可以从1 (i = 1)开始计数,因为您声明必须给出一个正整数。
h = int(input('insert positive integer: '))
i = 1
total = 0
while total <= h:
total += i ** 2
i += 1
print(total)
发布于 2016-02-07 09:54:30
您关心的是n**2
的当前值是否小于h
。所以一定要测试这个值。
h = 19
n = 1
q = 0
while n**2 <= h:
q += n**2
n += 1
print("Sum of squares less than {} is: {}".format(h, q))
https://stackoverflow.com/questions/35248068
复制相似问题