|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 mumei2018 于 2023-5-1 22:42 编辑
nums = []
IsInput = True
while IsInput == True:
e_a = input("enter a number(enter S to stop):")
if e_a != 'S':
nums.append(e_a)
print(nums)
else:
IsInput = False
target = int(input("enter a target:"))
IsFind = False
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
print([i, j])
IsFind = True
if IsFind == False:
print('not found.')
运行结果如下
= RESTART: C:/Users/Administrator/AppData/Local/Programs/Python/Python311/hw/019b1a.py
enter a number(enter S to stop):80
['80']
enter a number(enter S to stop):20
['80', '20']
enter a number(enter S to stop):S
enter a target:100
not found.
本帖最后由 sfqxx 于 2023-5-1 22:38 编辑
根据代码运行结果,可以发现没有找到两个数的和为目标值,提示 "not found." 。这说明程序中存在问题,具体来说应该是在计算两个数的和时出了错误。
分析代码可以发现,在循环中计算两个数的和时使用了错误的加法操作 nums + nums[j],而实际上应该是 int(nums) + int(nums[j])。因此需要将代码中的这一行
- [/i][/b][b][i]if nums + nums[j] == target:
复制代码
改为
- [/i][/b][b][i]if int(nums[i]) + int(nums[j]) == target:[/i][/i][/b][b][i]
复制代码 [i]
另外,需要注意将输入的字符串转换为整数类型,可以使用 int() 函数实现。最终修改后的代码如下所示:
- nums = []
- IsInput = True
- while IsInput == True:
- e_a = input("enter a number(enter S to stop):")
- if e_a != 'S':
- nums.append(int(e_a))
- print(nums)
- else:
- IsInput = False
- break
- target = int(input("enter a target:"))
- IsFind = False
- n = len(nums)
- for i in range(n):
- for j in range(i + 1, n):
- if int(nums[i]) + int(nums[j]) == target: # 修改此处
- print([i, j])
- IsFind = True
- if IsFind == False:
- print('not found.')
复制代码
经过修改后,程序就能够正确地输出符合要求的结果。希望对你有所帮助!
有用请设置最佳答案[/i]
|
-
|