如何获取我的代码来查找中间号码?每当我运行代码时,我都可以输入所需的数字,但它不会告诉我中间数字是什么。
public static int middleArray(int values[])
{
//reading numbers into the array
int [] ma = new int [0];
int middleArray;
if(values.length % 2 == 0)
{
int num1=(values.length-1)/2;
int num2 = values.length/2;
middleArray = ( values[num1] + values[num2])/ 2;
return middleArray;
}
else
{
int num = (values.length - 1) / 2;
middleArray = values[num];
}
return middleArray;
}
public static void main() {
Scanner s = new Scanner(System.in);
System.out.println("Enter a series of numbers to determine middle
number");
int middleArray = s.nextInt();
}
}
答案 0 :(得分:0)
看着你的代码,我在跟踪代码时遇到了麻烦,看起来你在计算某些东西时做错了数学
int num1=(values.length-1)/2;
int num2 = values.length/2;
middleArray = ( values[num1] + values[num2])/ 2;
您将数组的长度添加到其自身,然后除以2。从本质上讲,取消了两次添加数组长度的操作。最重要的是,您甚至从未在主循环内调用函数,也没有办法关闭输入。
用于获取一组未排序数字中位数的代码的有效版本将是这样(我摆脱了扫描仪,因为这种用户输入变得复杂,我认为您尚未达到该水平):>
public static double takeMiddleOfArr(int values[]) {
double output = 0; //Initialize output
if(values.length % 2 != 0) { //See if the array is even or odd
output = values[(int)Math.floor(values.length/2)]; //If odd just output middle element
} else {
double mid = values.length/2.0; //Finds middle element of array
output = (values[(int)(mid-1)]+values[(int)(mid)])/2; //If even take avg of middle elements
}
return output;
}
public static void main(String[] args) {
int[] array = {1,2,3,4,20,6,3,2,1}; //Input array
System.out.println(takeMiddleOfArr(array)); //Prints outout
}
答案 1 :(得分:0)
获取中间数字的原始代码计算逻辑为(values.length-1)/ 2,而应为[(values.length / 2)-1]。如果有两个数字,则这两个数字将被打印为中间数字。请尝试下面的代码提供示例测试结果。
代码:
public class middleNum {
public static void main(String args[]) throws Exception {
int[] first= new int[] {1,2};
int[] second= new int[] {1,2,3};
int[] third= new int[] {1,2,3,4};
int[] fourth= new int[] {1,2,3,4,5};
System.out.println(Arrays.toString(getMiddleNum(first)));
System.out.println(Arrays.toString(getMiddleNum(second)));
System.out.println(Arrays.toString(getMiddleNum(third)));
System.out.println(Arrays.toString(getMiddleNum(fourth)));
}
public static int[] getMiddleNum(int[] nums) {
int[] ma;
if (nums.length %2 == 0) {
// if the array length is even then there are two middle numbers
ma = new int[2];
ma[0] = nums[(nums.length/2) - 1];
ma[1] = nums[nums.length/2];
} else {
// if the array length is odd then there is one middle number
ma = new int[1];
ma[0] = nums[nums.length/2];
}
return ma;
}
}
Output:
[1,2]
[2]
[2,3]
[3]