2个数字范围的总和是多少?
我想总结两个数字之间的值的范围。我提示用户输入2个号码,如果第一个号码大一些,我想在循环前用第二个号码交换。我怎样才能做到这一点?2个数字范围的总和是多少?
import java.util.Scanner; public class Example {
public static void main (String []args) {
Scanner kb = new Scanner(System.in);
int n1 = 0, n2 = 0, count = 0;
System.out.print("Enter two limits: ");
n1 = kb.nextInt();
n2 = kb.nextInt();
while (n1 <= n2) {
count = count + n2;
n2--;
}
System.out.println("The sum from "+ n1 +" to "+ n2 +" is : " + count);
}
}
,我想输出告诉我(如果I型6和10)
the sum from 6 to 10 is 40
,但我的程序输出
the sum from 6 to 5 is 40
我在做什么错?
回答:
您可以使用Math.max(int, int)
和Math.min(int, int)
(和IntStream
,您使用的是Java假设8+)。像,
Scanner kb = new Scanner(System.in); System.out.print("Enter two limits: ");
int n1 = kb.nextInt();
int n2 = kb.nextInt();
int start = Math.min(n1, n2), stop = Math.max(n1, n2);
System.out.println("The sum from " + n1 + " to " + n2 + " is : "
+ IntStream.rangeClosed(start, stop).sum());
如果您不能出于某种原因,还是很方便的小动作使用Math
,你可以做一些数学自己的;像
int start = n1; if (n2 < n1) {
start = n2;
}
int stop = n2 + n1 - start;
或
int start = (n1 < n2) ? n1 : n2, stop = n2 + n1 - start;
回答:
Scanner in = new Scanner(System.in); int n1;
int n2;
int count = 0;
System.out.print("Enter two limits: ");
n1 = in.nextInt();
n2 = in.nextInt();
if (n1 > n2) {
n1 += n2;
n2 = n1 - n2;
n1 -= n2;
}
int current = n1;
while (current <= n2) {
count += current;
current++;
}
System.out.println("The sum from " + n1 + " to " + n2 + " is : " + count);
以上是 2个数字范围的总和是多少? 的全部内容, 来源链接: utcz.com/qa/258998.html