我必须编写一个程序,将两个边界之间的所有奇数相加。我得到它来添加奇数,但是如果其中一个界限是负数,我就无法让它工作。这是我已经拥有的代码。
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
。
关于java - 奇数求和不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36167732/