新数组中找出所有的奇数元素并求和
int []arr={12,0,45,0,3,0,23,8,45,8};去除arr数组中的0元素,并生成一个新数组,并在新数组中找出所有的奇数元素并求和 class Solution {
public static void sumOddElements(int[] arr){
List<Integer> newList = new ArrayList<>();
int sum = 0;
for(int idx = 0; idx < arr.length; idx++){
int num = arr;
if(num != 0){
if(num % 2 == 1) sum += num;
newList.add(num);
}
}
System.out.println("new list: " + newList);
System.out.println("sum of odd elements: " + sum);
}
} import java.util.Scanner;
public class deom1 {
public static void main(String[]args){
//接收数组的长度
int []arr={12,0,45,0,3,0,23,8,45,8};
int count=0;
for (int i=0;i<arr.length;i++){
if (arr!=0){
count++;
}
}
//创建数组,新数组的长度就是非元素的个数
int[]newArr =new int;
//把arr数组中的非元素给newArr数组进行赋值
//给newArr数组声明一个新下标求进行赋值
int index=0;
for (int i=0;i<arr.length;i++) {
if (arr != 0) {
newArr = arr;
//newArr=arr; ArrayIndexOutOfBoundException :下标越界
newArr = arr;
/**
* index i
* 0 0 12
* 1 2 45
*/
index++;
}
}
//在newArr数组中找出奇数元素
//声明一个变量来表示奇数和
int sum=0;
for (int i=0;i<newArr.length;i++){
if (newArr%2!=0){
sum+=newArr;
}
}
System.out.println("当前arr数组中的奇数和为:"+sum);
}
}
#include <stdio.h>
#include <stdlib.h>
#define length(arr) (sizeof(arr)/sizeof(arr))
int main()
{
int arr[]= { 12,0,45,0,3,0,23,8,45,8 };
int len = length(arr);
for (int i = 0; i < len; i++)
{
if (arr == 0)
{
for (int j = i; j < len; j++)
{
arr = arr;
}
len--;
}
}
int num = len;
int *new_arr;
new_arr = (int*)malloc(len * sizeof(int));
int sum = 0;
printf("新数组为: ");
for (int i = 0; i < len; i++)
{
new_arr = arr;
if (new_arr % 2 != 0)
{
sum += new_arr;
}
printf("%d ", new_arr);
}
printf("\n奇数和为: %d \n", sum);
} public static int[] deleElement(int arr[], int ele){
int newArr[]=new int;
int j=0, zero=0;
for(int i=0; i<arr.length; i++){
if(arr==ele) {
zero++;
continue;
}
newArr=arr;
}
int newLen = newArr.length-zero;
int resArr[] = new int;
System.arraycopy(newArr, 0, resArr, 0, newLen);
return resArr;
}
public static int sumOdd(int arr[]) {
int sum=0;
for(int i=0; i<arr.length; i++) {
if (arr%2!=0) {
sum+=arr;
}
}
return sum;
}
int arr[]={12,0,45,0,3,0,23,8,45,8};
int newArr[] = deleElement(arr, 0);
int sum = sumOdd(newArr);
System.out.println(sum);
页:
[1]