【问题标题】:how to create an array of 5 elements dynamically and print the sum of all elements in end?如何动态创建一个包含 5 个元素的数组并在最后打印所有元素的总和?
【发布时间】:2023-02-20 23:32:54
【问题描述】:

当我尝试相同的逻辑并使用 for 循环执行时它起作用,而当我尝试相同的使用 for 每个循环时它没有给出预期的结果。当我尝试在最后打印所有元素的总和时,它给出了答案 0。

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of array");
        float n = sc.nextFloat(); float sum=0;
        float []a =new float[5];
        System.out.println("Enter the elements of array");
        for(float element : a)
        {
            element = sc.nextFloat();
        }
        System.out.println("The sum of the items in array are:");
        for(float element : a)
        {
           sum = sum + element; 
           
        }
        System.out.println(sum);
        
    }
}

【问题讨论】:

标签: java


【解决方案1】:

到处都是一些小错误,请参阅:

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of array");
        int n = sc.nextInt();
        float sum = 0;
        float[] a = new float[n];
        System.out.println("Enter the elements of array");
        int i = 0;
        while (i < n) {
            a[i++] = sc.nextFloat();
        }
        System.out.println("The sum of the items in array are:");
        for (float element : a) {
            sum = sum + element;
        }
        System.out.println(sum);

    }
}

祝你年轻的 padawan 在你的道路上好运!

【讨论】:

    猜你喜欢
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 2016-04-26
    • 2020-04-15
    相关资源
    最近更新 更多