如何解决如何不计算负输入
有没有一种方法可以使计数器不计负数而仅在输入为零时才停止计数?
count = 0
total = 0
n = input()
while n != '0':
count = count + 1
total = total + int(n) ** 2
n = input()
print(total)
这是执行结果的一个例子。
输入:-1 10 8 4 2 0
输出:184
解决方法
您可以将输入解析为一个整数(数字),然后检查它是否大于零:
count = 0
total = 0
num = int(input())
while number != 0:
if number < 0:
continue
count += 1
total = total + num**2
num = int(input())
print(total)
通过,继续,中断和返回之间的区别是:
- pass =忽略我,只是继续进行,对创建尚无目的的函数很有用
- continue =忽略循环中的所有其他内容并开始新的循环
- break =打破循环
- return =函数的结尾-return语句可用于向函数提供输出,但也可以像break语句在循环中一样作为脱离函数的方式。
- 由于只希望数字输入
loop
,因此可以使用内置的isnumeric()
进行检查。 - 您需要在这里
if() : break
。
num = input()
...
while(isnumeric(num)):
...
if(num == "0"):
break;
,
您等待的答复是:
- 忽略负数
- 计算正数
- 在输入为
0
时停止
count = 0
total = 0
n = int(input())
while (n != 0):
count += 1
if (n > 0):
total = total + n**2
num = int(input())
print(total)
您的代码已经可以,只是您没有将数字n
强制转换为int
,并且没有测试n
来消除负值。
执行:
输入-1 10 8 4 2 0
时,它应显示184
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。