gpt4 book ai didi

java - 两个数字之间的和(包括之间的数字)

转载 作者:行者123 更新时间:2023-11-30 06:04:55 24 4
gpt4 key购买 nike

我正在尝试获取两个数字以及它们之间的所有数字的总和。我的麻烦是确保第一个或第二个输入是否更大并不重要。这就是我到目前为止所得到的。

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;
}
}
}
}

最佳答案

使用此公式求系列总和:

n/2*{2*a+(n-1)*d}

其中n = 总术语/数字
a = 第一项/数字
d = 两个相邻数字之间的差

关于java - 两个数字之间的和(包括之间的数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48125800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com