简体   繁体   English

int low和int high之间的数字总和; 爪哇

[英]Sum of numbers between int low and int high; Java

I am trying to create a code in Java and I know this is wrong but I need a little help: 我正在尝试用Java创建代码,但我知道这是错误的,但是我需要一些帮助:

Given two integers low and high representing a range, return the sum of the integers in that range. 给定两个低和高整数,它们代表一个范围,则返回该范围内整数的总和。 For example, if low is 12 and high is 18, the returned values should be the sum of 12, 13, 14, 15, 16, 17, and 18, which is 105. If low is greater than high, return 0. 例如,如果low为12而high为18,则返回的值应为12、13、14、15、16、17和18的总和,即105。如果low大于high,则返回0。

The solution I have is (I know it's not right, don't murder me pls): 我的解决方案是(我知道这是不对的,请不要谋杀我):

public int sumRange(int low, int high)
{
    int sum = 0;
    for (int val = int low; val < int high; val++)
        sum += val;
    return val;
}

You have several issues. 你有几个问题。

  1. Incorrect loop syntax. 错误的循环语法。 You don't need to redeclare the type of existing variables. 您无需重新声明现有变量的类型。
  2. You return val instead of sum . 您返回val而不是sum Since val is scoped to the loop, this is a compile error. 由于val的作用域是循环,因此这是编译错误。
  3. Your loop ends one too early. 您的循环结束得太早了。 It doesn't include the largest value. 它不包括最大值。 To include it use <= rather than < . 要包含它,请使用<=而不是<

Fixed code 固定码

public class RangeTest1 {

    public static void main(String[] args){

        System.out.println(sumRange(12, 18)); // prints 105
        System.out.println(sumRange(18, 12)); // prints 0
        System.out.println(sumRange(18, 18)); // prints 18
    }

    public static int sumRange(int low, int high)
    {
        int sum = 0;

        for (int val = low; val <= high; val++){
            sum += val;
        }

        return sum;
    }
}

You get the 0 if low is greater than high for free, as the loop never runs any iterations if this is the case. 如果low免费大于high免费,则得到0,因为在这种情况下,循环永远不会运行任何迭代。 The initial value of 0 remains and is returned. 初始值0保留并返回。

Or you could use math , although you have to be careful of overflow if high is very large: 或者,您可以使用数学运算法则 ,但是如果high很大,则必须小心溢出:

public static int sumRange(int low, int high)
{
  return high >= low ? (high*(high+1) - low*(low-1))/2 : 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM