我试图得到两个数字和它们之间所有数字的总和。我的麻烦在于确保第一个或第二个输入更大是不重要的。这是我到目前为止所做的。
import java.util.Scanner;
public class BoundedSum
{
static Scanner input = new Scanner(System.in);
static int sum = 0;
static int first;
static int second;
public static void main(String[] args)
{
System.out.println("Input an integer (0,1,2,3...).");
first = input.nextInt();
System.out.println("Input a second integer. The sum of your inputs\nplus any numbers between them will be given.");
second = input.nextInt();
while(true)
{
if(first < second)
{
sum += first;
first++;
}
if(second < first)
{
sum += second;
second++;
}
if(first == second || second == first)
{
System.out.println("The sum = " + sum);
break;
}
}
}
}
答案 0 :(得分:3)
将此公式用于系列总和:
n/2*{2*a+(n-1)*d}
其中n
=总条款/数字
a
=第一个词/号码
d
=两个相邻数字之间的差异
答案 1 :(得分:2)
您正在有效地尝试计算sum of an arithmetic progression。公式中唯一“缺失”的部分是元素的数量,可以通过减去两个边界轻松推断出来:
int sum = (Math.abs(first - second) + 1) * (first + second) / 2;
答案 2 :(得分:0)
你想从低级到高级循环,我会做类似的事情。
int low, high;
if(first<second){
low = first;
high = second;
} else{
low = second;
high = first;
}
然后进行循环:
for(int i = low; i<=second; i++){
}
当然,等式更快,但这似乎解决了你的问题。