如何获得一个循环中m和n之间所有整数的和?

编程入门 行业动态 更新时间:2024-10-25 22:27:15
本文介绍了如何获得一个循环中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之间所有整数的和?

本文发布于:2023-11-29 23:36:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647971.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   如何获得

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!