如何获得一个循环中m和n之间所有整数的和? [英] How to get the sum of all integers between m and n in a loop?

查看:47
本文介绍了如何获得一个循环中m和n之间所有整数的和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在获取 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之间所有整数的和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆