[英]Odd summation not working
我必須編寫一個程序,將兩個邊界之間的所有奇數相加。 我得到它加上奇數,但是如果其中一個界限是負數,我就無法使它起作用。 這是我已經擁有的代碼。
import java.util.Scanner;
/**
Computes a sum of odd integers between two bounds.
Input: a, the lower bound (may be odd or even).
Input: b, the upper bound (may be odd or even).
Output: sum of odd integers between a and b (inclusive).
*/
public class OddSum
{
public static void main(String[] args)
{
// Read values for a and b
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int sum = 0;
int swap;
if(a > b) {
swap = a;
a = b;
b = swap;
}
for (int i = a; i <=b; i++){
if (i % 2 ==1)
sum +=i;
}
System.out.println(sum);
}
}
令人討厭的是,奇數的條件是
n % 2 != 0
n % 2 == 1
不適用於負奇數,因為n % 2
給出-1
。
與其在每個循環迭代中測試i
的奇數,不如建議您從范圍內最小值之后的第一個奇數開始,然后在循環中增加2。 就像是,
int a = in.nextInt();
int b = in.nextInt();
int lo = Math.min(a, b);
int hi = Math.max(a, b);
if (lo % 2 == 0) { // <-- ensure that lo is odd.
lo++;
}
int sum = 0;
for (int i = lo; i <= hi; i += 2) {
sum += i;
}
System.out.println(sum);
您需要使用i % 2 != 0
作為條件來檢查數字是否為奇數,因為不幸的是,您當前正在使用的條件不適用於負數。
在確定a或b應該是第一個之后,可以使用IntStream
在一行中IntStream
:
int sum = IntStream.rangeClosed(a, b).filter(i -> i % 2 != 0).sum();
這將取所有奇數之和。 別忘了導入
import java.util.stream.IntStream;
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.