首页 > 解决方案 > 如何将整数 n 的总和添加到 c

问题描述

我想编写一个代码,打印出指定数字、另一个指定数字以及介于两者之间的所有内容(包括)的总和。例如,如果我们有数字 (6, 8),它应该将数字 6、7 和 8 相加,并打印总和 21。有人可以向我解释我应该如何去做吗?

标签: javamath

解决方案


您可以通过使用循环和据我了解的单独方法来做到这一点,我们将其称为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;
  }
}

推荐阅读