简体   繁体   English

使用循环的简单程序(从Java开始)

[英]Simple program using loops (Beginning Java)

I have to write a program using loops that calculates the sum of all odd numbers between a and b (inclusive), where a and b are inputs. 我必须编写一个使用循环的程序,该程序计算a和b(含)之间所有奇数的和,其中a和b为输入。

I made this (below) and it works fine, but I noticed one problem with it: when i enter a larger number followed by a smaller number for the inputs, it returns 0, but when i enter the smaller number first it works perfectly. 我做了这个(下图),它工作正常,但是我注意到了一个问题:当我输入一个较大的数字,然后输入一个较小的数字时,它返回0,但是当我首先输入较小的数字时,它可以正常工作。 Any quick fixes for this? 有任何快速解决方案吗? :) :)

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);
   }
}
int temp;
if(a > b) {
    temp = a;
    a = b;
    b = temp;
}

Put this right before your for loop starts. 将其放在您的for循环开始之前。


The if checks whether a (the first number entered) is larger than b . if检查a (输入的第一个数字)是否大于b If it is, it swaps a and b . 如果是,它将交换ab Now your for loop will always start with the smallest number and iterate up to the larger number (because after this if , a will always be the smaller number). 现在,您的for循环将始终从最小的数字开始,然后迭代到更大的数字(因为在此之后, if a始终是较小的数字)。

Using this method has the added side effect of making your output make sense. 使用此方法具有使输出有意义的附加副作用。 Your output will now always say: "between [smaller number] and [larger number]" . 现在,您的输出将始终显示: "between [smaller number] and [larger number]"

rolfl's answer is more elegant and works perfectly fine, but when the user enters the larger number first, your output may look kind of weird: "between [larger number] and [smaller number]" , etc. rolfl的答案更优雅,而且效果很好,但是当用户首先输入较大的数字时,您的输出可能看起来很奇怪: "between [larger number] and [smaller number]"

You can get the smaller and larger inputs by using the Math.min() and Math.max functions.... 您可以使用Math.min()Math.max函数获得越来越小的输入。

for (int j = Math.min(a,b); j <= Math.max(a,b); j++) {
    if (j % 2 == 1) {
        sum += j;
    }
}

It's not working because A is larger than B in the for loop, you have it iterate while A is less than or equal to B . 它不起作用,因为在for循环中A大于B ,而在A小于或等于B时进行迭代。

You could do what nhgrif says but it's changing your data.. But he is correct. 您可以执行nhgrif所说的,但是它正在更改您的数据。。但是他是正确的。

That's because you are first expecting for the a input (inferior limit) and then the b (superior). 那是因为你首先期待的a输入(逊色限制),然后b (上级)。 When your program reaches the for , j = a so the condition a <= b is False, if the first input is larger. 当程序到达forj = a因此如果第一个输入较大,则条件a <= b为False。 In other words it never enters the for loop. 换句话说,它永远不会进入for循环。

Actually you should do the following 2 things: 实际上,您应该做以下两件事:

1 It is just just like rolfl mentioned above. 1就像上面提到的rolfl一样。 You need to put the min and max in the right place in loop. 您需要将min和max循环放置在正确的位置。

for (int j = Math.min(a,b); j <= Math.max(a,b); j++) { for(int j = Math.min(a,b); j <= Math.max(a,b); j ++){

if (j % 2 == 1) {
    sum += j;
}

} }

2 Use if (j % 2 == 1) it is not enough to check whether the num is odd. 2使用if(j%2 == 1)不足以检查num是否为奇数。

eg 例如

a = -5 , b =0; a = -5b = 0; What will be the result? 结果如何?

    int sum = 0;
    for(int j=-5;j<0;j++)
    {
        if(j%2 == 1)
        {
            sum+=j;
        }
    }

The value for sum will be 0. sum的值为0。

We need to change the condition to if(!(j%2 == 0)) Then you will get the expected result. 我们需要将条件更改为if(!(j%2 == 0))然后,您将获得预期的结果。

That's because you are first expecting for the a input (inferior limit) and then the b (superior). 那是因为您首先期望输入(下限),然后是b(上级)。 When your program reaches the for, j = a so the condition a <= b is False, if the first input is larger. 当程序到达for时,j = a,因此,如果第一个输入较大,则条件a <= b为False。 In other words it never enters the for loop. 换句话说,它永远不会进入for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM