如何在Java中找到数组中所有数字的总和?
您可以使用循环找到数组所有元素的总和。创建一个初始值为0的count变量,迭代循环直到数组结束,然后将每个元素添加到count中。
示例
import java.util.Arrays;
import java.util.Scanner;
public class SumOfAllNumbers {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int count = 0;
System.out.println("Enter the size of the array that is to be created:: ");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i=0; i<size; i++) {
myArray[i] = sc.nextInt();
count = count+myArray[i];
}
System.out.println("Array is :: "+Arrays.toString(myArray));
System.out.println("Sum of all numbers in the array is :: "+count);
}
}输出结果
Enter the size of the array that is to be created:: 5 Enter the elements of the array :: 45 56 85 78 99 Array is :: [45, 56, 85, 78, 99] Sum of all numbers in the array is :: 363
热门推荐
6 甄嬛传祝福语简短
10 岁岁祝福语简短独特
11 送给员工美好祝福语简短
12 结婚祝福语亲姐姐简短
13 冬季祝福语大全 简短的
14 高中升学宴祝福语简短
15 对上司的简短祝福语
16 小考加油文案祝福语简短
17 妈妈生日祝福语简短温暖
18 简短祝福语乔迁新家贺词