2017-12-03 6 views
0

2つの数値の間の値の範囲を合計します。ユーザーに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); 
    } 
} 

と私が欲しいの出力は、(私は6と10を入力した場合)私に語っ

the sum from 6 to 10 is 40 

が、私のプログラムの出力は

the sum from 6 to 5 is 40 

私が間違って何をやっているのですか?

+0

申し訳ありませんが、 ' – mmmmmzdsdsd5555

+1

低いですn2 - 'は入力値を減らしています – ti7

答えて

3

あなたは(8+は、Javaを使用していると仮定して、IntStreamMath.max(int, int)Math.min(int, int)を使用することができます。あなたには、いくつかの理由、または非常に便利な小さなトリックをMathを使用できない場合と同様に、

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()); 

、あなたはあなた自身のいくつかの数学を行うことができます。ユーザ入力が大きな最初のプログラムは、最初の数であるように番号を交換する必要がある場合は私のミスが、私が意味することのような

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

または

int start = (n1 < n2) ? n1 : n2, stop = n2 + n1 - start; 
0
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); 
関連する問題