【发布时间】:2013-11-06 01:28:17
【问题描述】:
我必须编写一个使用循环计算 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);
}
}
【问题讨论】:
-
只有两个输入不需要for循环,也可以用数组代替。
-
使用 if (j % 2 == 1) 来检查 num 是否为奇数是不够的。例如 a = -5, b =0;结果会怎样?它为零。你需要把条件改成 if(!(j%2 == 0)) 然后你会得到预期的结果。
-
这个问题有几个很好的答案。您应该考虑将其中一项标记为已接受。