我认为我已经相互交换了动态数组的第一个和最后一个数字,并且完全不知道如何使用交换的数字打印数组。
理想情况下,在程序运行时,用户应输入他们想要输入的数字,然后他们将单独输入每个数字。 然后它应该按顺序输出(以及标准偏差,平均值和原始数组顺序)数组,除了输入的第一个数字和输入的最后一个数字。您将如何使用切换的数字打印新阵列?
到目前为止,这是我的代码:
import java.util.Scanner;
import java.lang.Math;
public class Project_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? ");
int N = scan.nextInt();
float sd, mean;
float Sum = 0;
float Square = 0;
float [] numbs = new float[N];
System.out.println("Enter your numbers below: ");
for (int i = 0; i < N; i++){
numbs[i] = scan.nextFloat();
Sum += numbs[i];
}
mean = Sum/N;
scan.close();
for (int j = 0; j < N; j++){
Square = (numbs[j] - mean) * (numbs[j] - mean);
}
sd = (float)Math.sqrt(Square/N);
System.out.println("The mean is: " + mean);
System.out.println("The standard deviation is: " + sd);
for (int k = 0; k < N; k++){
if (k == N-1){
System.out.print(numbs[k]);
}else{
System.out.print(numbs[k] + ", ");
}
}
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
}
}
答案 0 :(得分:0)
您可以通过执行以下操作来交换整数,
int temp = numbs[N-1];
numbs[N-1] = numbs[0];
numbs[0] = temp;
希望这会有所帮助:)
答案 1 :(得分:0)
我没有意识到我只需要输入另一个简单的if语句来打印出来。我对编辑过的数组保存到的位置感到困惑,没有意识到它只是保存到原始数组。谢谢大家的帮助。
最后这是我用于代码的内容(特别是关于我的程序):
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-atinject_1.0_spec</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
继承人的输出:
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
for (int g = 0; g < N; g++){
if (g == N-1){
System.out.print(numbs[g]);
}else{
System.out.print(numbs[g] + ", ");
}