我在获取 m 和 n 之间的所有整数的总和时遇到问题.在代码中,我必须输入两个整数 m 和 n ,并计算并显示从 m 到的所有整数的和.n .
I am having problems acquiring the sum of all integers between m and n. In the code, I must input two integers m and n, and calculate and display the sum of all the integers from m to n.
应该使用循环将总和重复加到数字上来计算总和,而我不能使用公式来计算结果.我到目前为止生成的代码显示在下面:
The sum should be calculated using a loop to repeatedly add numbers to a total and I cannot use a formula to calculate the result. The code I produced so far is displayed below:
m = int(input("Enter a number: ")) n = int(input("Enter a second number: ")) sum = 0 for i in range (m,n): m+n sum += i print(i) 推荐答案您应该使用 range(m,n + 1)以便将 n 包含在范围内
You should use range(m, n+1) in order to include n in the range.
for i in range (m,n+1): s += i print(i) print(s)例如 range(4,6)将给您 [4,5] ,但是 range(4,5)将给您仅 [4] .
For example range(4,6) will give you [4,5] but range(4,5) will give you only [4].
更多推荐
如何获得一个循环中m和n之间所有整数的和?
发布评论