如何在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
热门推荐
1 训练狗狗搜寻
2 如何训练狗狗装死
3 狗狗训练书
6 怎么训练狗狗拜年
8 狗狗训练游戏
10 狗狗嗅觉训练
11 怎么训练狗狗在笼子里不叫
12 怎么训练狗狗站立走路
13 怎么训练狗狗在马桶上
14 狗狗尿尿怎么训练
15 训练狗狗用品
16 泰迪狗狗的训练方法大小便
17 训练狗狗可以打吗
18 王曼丽的狗狗训练