[英]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.