gpt4 book ai didi

java - 我有一个 double 组,我需要得到一个中位数,但它一直给我一个 int 转换错误

转载 作者:行者123 更新时间:2023-11-30 08:31:38 25 4
gpt4 key购买 nike

如果没有这种方法,我不知道如何获得中位数,但它一直说转换错误。我知道这是因为我将 numbers.length 除以 2,但我不知道如何让程序理解它是一个 double 。它在我不断收到错误的底部。这是我的最后一个 if else 语句。我到处搜索,如果这是重复的,我很抱歉,但我找不到。我也无法转换为整数,因为我的数组由 double 组成。在此先感谢帮助我的人。

import static java.lang.Math.*;
import java.util.Scanner;
import java.util.Arrays;
public class ComputingArrays
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);

double [] numbers = {33.5, 67.5, 67.5, 88.0, 46.0, 94.5, 77.5, 83.0, 95.0, 80.5}; // declare, allocate memory, and store values

double n = numbers.length; // get length of array
Arrays.sort(numbers);
System.out.println("The Array of Numbers are :");
double sum = 0; //initiate and declare sum
for (int i = 0; i < n; i++) { //loop through n numbers
System.out.println(numbers[i]);
sum = sum + numbers[i];
}
final double average = sum / n;
System.out.println("The Sum of the Array is " + sum);
System.out.println("The Average of the Array is " + average);

double var1 = 0;
double var2 = 0;
double varSum = 0;
for (int i = 0; i < n; i++) {
var1 = numbers[i] - average;
var2 = var1 * var1; // to square
varSum = varSum + var2; // to get sum of all squared differences
}
double variance = varSum / n;
System.out.printf("The Variance of the Array is %.2f %n", variance); //%.2f rounds two decimal places

System.out.printf("The Standard Deviation is %.3f %n", Math.sqrt(variance));

double middle = numbers.length / 2.0;
double median = 0.0;
if (numbers.length % 2 == 1){
median = numbers[middle];
System.out.println("The median is " + median);
}
else {
median = (numbers[middle-1] + numbers[middle]) / 2;
System.out.println("The median is " + median);
}
}
}

最佳答案

当索引数组时,它需要 int 而不是 double,因为像 5.5 这样的值不是有效索引。

有效

int middle = numbers.length / 2;
System.out.println(numbers[middle]);

无效

double middle = numbers.length / 2.0;
System.out.println(numbers[middle]);

关于java - 我有一个 double 组,我需要得到一个中位数,但它一直给我一个 int 转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40567554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com