我必须编写一个程序,使用循环计算 a 和 b(包括)之间所有奇数的总和,其中 a 和 b 是输入。
我做了这个(如下),它工作正常,但我注意到它有一个问题:当我输入一个较大的数字,然后输入一个较小的数字时,它返回 0,但是当我首先输入较小的数字时,它工作得很好。对此有任何快速修复吗?:)
import java.util.Scanner;
public class ComputeSumAAndB
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter 2 integers: "); //prompts user for ints
int a = in.nextInt();
int b = in.nextInt();
int sum = 0;
for (int j = a; j <= b; j++)
{
if (j % 2 == 1)
sum += j;
}
System.out.println("The sum of all odd numbers (inclusive) between " + a + " and "+ b + " is " + sum);
}
}