【问题标题】:What is the sum of the range of 2 numbers?2个数的范围之和是多少?
【发布时间】:2017-12-03 00:33:24
【问题描述】:

我想对两个数字之间的值范围求和。我提示用户输入 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);
    }
}

我想要的输出告诉我(如果我输入 6 和 10)

the sum from 6 to 10 is 40

但我的程序输出是

the sum from 6 to 5 is 40

我做错了什么?

【问题讨论】:

  • 对不起我的错误,但我的意思是如果用户首先输入较大的程序应该将数字交换为第一个数字较低
  • n2-- 正在减少您的输入值

标签: java loops sum int


【解决方案1】:

可以使用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,或者一个非常方便的小技巧,你可以自己做一些math;喜欢

int start = n1;
if (n2 < n1) {
    start = n2;
}
int stop = n2 + n1 - start;

int start = (n1 < n2) ? n1 : n2, stop = n2 + n1 - start;

【讨论】:

    【解决方案2】:
    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);
    

    【讨论】:

      猜你喜欢
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2019-06-20
      • 2023-03-25
      • 2016-02-22
      相关资源
      最近更新 更多