java - 奇数求和不起作用

标签 java algorithm

我必须编写一个程序,将两个边界之间的所有奇数相加。我得到它来添加奇数,但是如果其中一个界限是负数,我就无法让它工作。这是我已经拥有的代码。

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/

相关文章:

c++ - 如何在插入排序中使用 replace() 使语句变得不必要

java - 内联 View 定义 Couch Db Ektorp

java - 在 Micronaut 休息端点的 JSON 中包含 null 和空属性

algorithm - 粗细算法

Java/Libgdx 自动磁贴

algorithm - N 次幂 n i-e n^n 是否是多项式? n^2 和 n^n 之间是否存在多项式差异?

java - 如何在 Java 中实现 rawurldecode?

java - 查找注册到某个操作的所有组件

java - setOnItemClickListener 自定义 Listview

algorithm - 单源最短双子路径