[英]Computing sum of values in array
我得到的问题是,用oddSum 输出的值与evenSum 相同,并且所有元素之和的值为0。
我不太清楚我哪里出错了,因为循环非常相似,如果偶数一个有效,其他的也应该?
无论如何,这是我的代码:
int evenData[] = new int [10];
int oddData[] = new int [10];
int sum = 0;
int evenSum = 0;
int oddSum = 0;
int[] data = {3, 2, 5, 7, 9, 12, 97, 24, 54};
for(int index = 0; index < data.length; index++)
{
if (data[index] % 2 == 0)
{
int temp = data[index];
data[index] = evenData[index];
evenData[index] = temp;
}
else
{
int temp = data[index];
data[index] = oddData[index];
oddData[index] = temp;
}
}
for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++)
{
evenSum =evenData[evenIndex] + evenSum;
}
System.out.print("Sum of even elements: " + evenSum);
for(int oddIndex = 0; oddIndex < oddData.length; oddIndex++)
{
oddSum = oddData[oddIndex] + oddSum;
}
System.out.print("Sum of odd elements: " + oddSum);
for(int index = 0; index < data.length; index++)
{
sum = data[index] + sum;
}
System.out.print("Sum of all elements: " + sum);
你得到相同的even
和odd
数值,因为你打印的是相同的值:-
System.out.print("Sum of odd elements: " + evenSum);
此外,您的最终总和zero
因为您将原始数组的所有元素都zero
,因为您将元素与evenData
和oddData
的元素交换,这些元素最初为零。
int temp = data[index];
data[index] = evenData[index]; // This code assigns a value 0 to current index.
evenData[index] = temp;
因此,您正在迭代数组,并为每个索引分配0
,同时将前一个元素添加到new array
。
我会说你不必要地使用了 2 个额外的数组和 3 个额外的循环。 为什么不在迭代原始数组的地方创建一个总和?
事实上,您所有的总和都可以在一个循环中计算:-
for(int index = 0; index < data.length; index++)
{
sum += data[index];
if (data[index] % 2 == 0)
{
// int temp = data[index];
// data[index] = evenData[index];
// evenData[index] = temp;
evenSum += data[index];
}
else
{
// int temp = data[index];
// data[index] = oddData[index];
// oddData[index] = temp;
oddSum += data[index];
}
}
System.out.println("Even Sum: " + evenSum);
System.out.println("Odd Sum: " + oddSum);
System.out.println("Total Sum: " + sum);
因此,您无需为even
和odd
创建额外的数组。
而且,您的4 loops
现在也已浓缩为一个循环。
int temp = data[index];
data[index] = evenData[index];
evenData[index] = temp;
查看上面的行, evenDate 是空的,在第二行中,您将数据数组设置为空。 您也在oddDate 行中重复了同样的错误。
你为什么不使用只是尝试以下?
for(int index = 0; index < data.length; index++)
{
if (data[index] % 2 == 0) {
int temp = data[index];
evenData[index] = temp;
} else {
int temp = data[index];
oddData[index] = temp; }
}
}
for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++)
{
//since length of all 3 data,even, odd arrays are the same
//you can put both sum operation in one for loop
evenSum = evenData[evenIndex] + evenSum;
oddSum = oddData[evenIndex] + oddSum;
sum = data[evenIndex] + sum;
}
System.out.print("Sum of even elements: " + evenSum);
//you have put evenSum for below odeUm printing in ur code
System.out.print("Sum of odd elements: " + oddSum);
System.out.print("Sum of all elements: " + sum);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.