java - 如何将整数 n 的总和添加到 c
问题描述
我想编写一个代码,打印出指定数字、另一个指定数字以及介于两者之间的所有内容(包括)的总和。例如,如果我们有数字 (6, 8),它应该将数字 6、7 和 8 相加,并打印总和 21。有人可以向我解释我应该如何去做吗?
解决方案
您可以通过使用循环和据我了解的单独方法来做到这一点,我们将其称为addSum
. 在 addSum 中,我们将创建一个带有起始限制和结束限制的 for 循环。
public static void addSum(int start, int end) {
int addMe = 0;
for(; start <= end; start++) {
addMe += start;
}
System.out.println("The result: " + addMe);
}
主要方法如下所示:
public static void main(String[] args) {
addSum(2, 4); // Replace this with the numbers you want
}
所以整个代码看起来像这样(假设你的文件名为 Main.java):
public class Main {
public static void main(String[] args) {
addSum(2, 4); // Replace this with the numbers you want
}
public static void addSum(int start, int end) {
int addMe = 0;
for(; start <= end; start++) {
addMe += start;
}
}
推荐阅读
- mysql - 在mysql中按结果更新/插入另一个表的组的列值
- ruby-on-rails - filterrific : 如何用多个词搜索查询?
- java - 为相同的休息端点提供两种方法,但在 Spring 中的 PathVariable 中有所不同
- android - Android 分页库重试 loadRange() 或 loadAfter()
- ruby-on-rails - ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):Rails 5
- javascript - 在 JavaScript 的日期数组中找不到日期
- android - 如何在 Ionic 源代码中指定用户权限
- python - 字符串到 int - 错误
- python - 绘制包含 NaN 值的 pandas 数据框列
- regex - Grep 中的正则表达式错误“重复之前没有有效的表达式”