测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A26848. 有关下面Python代码的说法,错误的是( )。def sqrt_binary(n, epsilon=1e-10): if n < 0: raise ValueError("输入必须为非负整数") if n == 0 or n == 1: return n # 阶段1: low, high = 1, n k = 0 while low <= high: mid = (low + high) //…

单选题 困难

题目描述

有关下面Python代码的说法,错误的是(    )。

def sqrt_binary(n, epsilon=1e-10):
	if n < 0:
		raise ValueError("输入必须为非负整数")
	if n == 0 or n == 1:
		return n

	# 阶段1:
	low, high = 1, n
	k = 0
	while low <= high:
		mid = (low + high) // 2
		mid_sq = mid * mid
		if mid_sq == n:
			return mid
		elif mid_sq < n:
			k = mid
			low = mid + 1
		else:
			high = mid - 1

	next_k = k + 1
	next_sq = next_k * next_k

	if next_sq == n:
		return next_k

	# 阶段2:
	low_float, high_float = float(k), float(k + 1)
	
	while high_float - low_float >= epsilon:
		mid = (low_float + high_float) / 2
		mid_sq = mid * mid
		
		if mid_sq < n:
			low_float = mid
		else:
			high_float = mid

	# 浮点数阶段后的最终结果
	result = (low_float + high_float) / 2

	check_int = int(result + 0.5)
	if check_int * check_int == n:
		return check_int
	return result

#测试示例
print(sqrt_binary(16)) # 输出: 4
print(sqrt_binary(17)) # 输出: ≈4.123
print(sqrt_binary(10**14)) # 输出: 10000000

选项(单选)

上一题 下一题