简体   繁体   English

奇数求和不起作用

[英]Odd summation not working

I have to write a program that adds all the odd numbers between two bounds. 我必须编写一个程序,将两个边界之间的所有奇数相加。 I got it to add the odd numbers, however I can't get it to work if one of the bounds is a negative. 我得到它加上奇数,但是如果其中一个界限是负数,我就无法使它起作用。 This is the code I have already. 这是我已经拥有的代码。

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);
   }
}

Annoyingly, the condition for an odd number is 令人讨厌的是,奇数的条件是

n % 2 != 0

n % 2 == 1 does not work for negative odd numbers because n % 2 gives -1 . n % 2 == 1不适用于负奇数,因为n % 2给出-1

Rather then testing i for oddness every loop iteration, I would suggest you start with the first odd number following your lowest value in range and then increment by 2 in the loop. 与其在每个循环迭代中测试i的奇数,不如建议您从范围内最小值之后的第一个奇数开始,然后在循环中增加2。 Something like, 就像是,

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);

You need to use i % 2 != 0 as your condition to check whether a number is odd or not because the condition you're currently using unfortunately won't work for negative numbers. 您需要使用i % 2 != 0作为条件来检查数字是否为奇数,因为不幸的是,您当前正在使用的条件不适用于负数。
After you've sorted out whether a or b should be first, you could get the sum in one line using IntStream : 在确定a或b应该是第一个之后,可以使用IntStream在一行中IntStream

int sum = IntStream.rangeClosed(a, b).filter(i -> i % 2 != 0).sum();

This will take the sum of all odd numbers. 这将取所有奇数之和。 Don't forget to import 别忘了导入

import java.util.stream.IntStream;

Cheers! 干杯!

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

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