【发布时间】:2019-05-17 17:05:02
【问题描述】:
我对数组和将它们分配给浮点等值有疑问。这是我的代码
System.out.print("Please enter the number of iteration: ");
Scanner scn = new Scanner(System.in);
int inumber = scn.nextInt(); // i get the iteration number
Random rnd = new Random();
float x = -10 + rnd.nextFloat() * 20; // i created random number between 10 and -10
System.out.println("My x = " +x);
float[] xarray = new float[4]; // created my test array
Random arrayrnd = new Random();
for (int i=0;i<inumber;i++) { // created a for loop with that number
for (int j = 0; j<xarray.length;j++) {
xarray[j] = arrayrnd.nextFloat(); // also created random for array and assigned them
}
Arrays.sort(xarray); // i sorted the array
xarray[0] = x; // i tried to assign the smallest number to x but didn't work
System.out.println("t="+i+" My new x = " +x);
这也是我的输出:
Please enter the number of iteration: 2
My x = -6.2841988
t=0 My new x = -6.2841988
t=1 My new x = -6.2841988
我只是不明白为什么我的 x 没有改变,即使我尝试为 x 分配新值。我希望我的 x 在循环的每一轮中都发生变化并获得数组的最小数量。但似乎 x 永远不想移动。如果我的代码很复杂或者我有任何错误,我很抱歉。编码愉快!
【问题讨论】:
-
如果你想改变它,你应该把
float x = -10 + rnd.nextFloat() * 20;移动到你的循环中 -
你一直在使用同一个 x,而不是新值
-
xarray[0] = x; // i tried to assign the smallest number to x but didn't work.----您不是将最小的分配给 x,而是将签证分配给虎钳