【发布时间】:2019-10-05 04:54:50
【问题描述】:
在将用户输入应用于整个数组时,我无法弄清楚如何根据用户输入递增元素。
问题:编写一个程序,创建一个双精度数组,其中数组的大小由用户提供。
用户还将提供数组的第一个值和一个增量值。 您的程序必须使用数组第一个元素的第一个值完全填充数组。 数组的下一个元素的值等于前一个元素加上增量。该程序基本上是生成一个算术级数。 数组填满后,必须打印以检查正确性。 您的程序必须针对任何合理的数组大小、起始值和增量值运行。
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.println("This program fills an array of doubles using an"
+ " initial value, the array size and an increment value.");
System.out.println("Please enter the desired size of the array: ");
int size = kbd.nextInt();
double[] array1 = new double[size];
System.out.println("Please enter the value of the first element: ");
array1[0] = kbd.nextDouble();
System.out.println("Please enter the increment value: ");
double inc=kbd.nextDouble();
double total =array1[0]+inc;
for (int i =0; i < array1.length;i++)
{
System.out.println(total++);
}
}
到目前为止,我的代码仅添加到第一个元素,但我不确定如何继续定位每个元素,以便输出如下所示:
此程序使用初始值、数组大小和增量值填充双精度数组。
Please enter the desired size of the array:6
Please enter the value of the first element: 0
Please enter the increment value:2
array[0]:0.00
array[1]:2.00
array[2]:4.00
array[3]:6.00
array[4]:8.00
array[5]:10.00
【问题讨论】:
-
我最初尝试过,这会将增量值应用于每个人请输入增量值:2 2.0 2.0 2.0 2.0 2.0 2.0
-
@ValerieJ 将
double total =array1[0]+inc;替换为 :double total = array1[0] ;并在 for 循环中这样做:for (int i = 1; i < array1.length; i++) { System.out.println(total + inc); total = total + inc; }