我有这个示例测验问题,但不确定如何使用 while 循环来处理它。
实现nearest_square函数。该函数采用整数参数 limit,并返回小于 limit 的最大平方数。
平方数是整数与其自身相乘的乘积,例如36是平方数,因为它等于6*6。
编写此代码的方法不止一种,但我建议您使用 while 循环!
您可以复制以下测试用例来测试您的代码。也可以随意编写额外的测试!
test1 = nearest_square(40)
print("expected result: 36, actual result: {}".format(test1))
Run Code Online (Sandbox Code Playgroud)
我已经设法解决了它。谢谢。
def nearest_square(limit):
limit = limit ** (0.5)
y = int (limit)
while y < limit :
y = y*y
return y
test1 = nearest_square(40)
print("expected result: 36,actual result:{}".format(test1))
Run Code Online (Sandbox Code Playgroud)
小智 5
尝试使用以下方法返回给定limit参数的最接近的平方:
def nearest_square(limit):
answer = 0
while (answer+1)**2 < limit:
answer += 1
return answer**2
Run Code Online (Sandbox Code Playgroud)