java - 循环遍历一个 int 数组并在其中使用模数

标签 java arrays modulo

我需要实现一种方法,该方法返回所有具有奇数索引的元素的交替总和减去所有具有偶数索引的元素的总和。返回的总和应为 -11 - 4 + 9 - 16 + 9 = -1

这是我的代码:

public class Arrays
{
public static void main(String[] args){

    int [] data = {1 ,4, 9, 16, 9};

    oddAndEven(data);
}

public static int[] oddAndEven(int[] data){
    int sum = 0;
    int sumA = 0;
    int index = data.length;
    for(int i:data){
    if(index % sumA == 1){
            sum = sum-i;
        }
    else{
        sum = sum+i;
    }
}
    System.out.println(sum);
    return sum;
    }
}

谁能告诉我哪里出错了?

这是一个类,请原谅我的基本代码和错误。

最佳答案

我会这样做:

public class test {
    public static void main(String[] args) {

    int [] data = {1 ,4, 9, 16, 9};
    oddAndEven(data);
}

public static void oddAndEven(int[] data) {

    int total = 0;

    for (int i = 0; i < data.length; i++)
    {
        if (i%2==0)
            total = total + data[i];
        else
            total = total - data[i];
    }

    System.out.println(total);
}
  1. 我已经摆脱了方法中的 return 并将其更改为 void(因为您正在打印其中的结果,所以不需要返回它。

  2. 您不需要两个不同的总和值,也不需要存储数组的长度。

  3. 使用总值并将其设置为 0。然后 for 循环遍历数组的长度。 %2 将数字除以 2 并确定余数。所以对于第一个循环,它将计算 0/2 并计算出余数(显然是 0)。当它 ==0 时,执行 for 循环中的第一个 if 语句(添加数字)。
    第二次通过时,它计算出 1/2,即 0 剩余 1 - 因此执行 else 语句,依此类推。

  4. 此外,请注意我是如何去掉 if 和 else 语句周围的大括号的。只要这些语句是一行,就不需要大括号——去掉 out 会使程序更易于阅读(在我看来)。显然,如果它们下面需要不止一行,则需要重新添加大括号。

关于java - 循环遍历一个 int 数组并在其中使用模数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14924285/

相关文章:

wolfram-mathematica - 在 Mathematica 中求解二次同余方程

java - Jprogressbar 不工作

java - junitreport : xslt fails with StackOverflowError when there are many newlines/linefeeds

java - 在我的程序中建立 URL 连接后未获取请求/响应中的值?

c++ - 数组 - 为什么下标运算符与标识符相关联?

terminology - "modulo"是动词吗?如果是,它是如何共轭的?

java - 在 jmockit 中模拟被测类的私有(private)方法

arrays - Swift UITableView 每 10 个单元格显示不同的单元格

javascript - 如何提取仅在 Javascript 中具有多个值的数组数据?

python - 在 python 中每 5 分钟运行一次与系统时钟同步的函数的最佳方法是什么?