gpt4 book ai didi

java - 如何在java中从 double 组创建char数组?

转载 作者:行者123 更新时间:2023-12-02 09:17:16 25 4
gpt4 key购买 nike

我有一个 double 组,其中包含代表期中考试成绩的值,我需要创建一个具有相同值的 char 数组,但我需要它来显示字母成绩。例如我需要从{89.6,73.9,96.9}到{B,C,A}。这是到目前为止我的代码:

  int numStudents = 60;
int studNum = 1;
double[] midtermGrades = new double[numStudents];
Scanner grades = new Scanner(System.in);

System.out.println("Here are the scores for the most recent test taken by your class:");


for (int i = 0; i < midtermGrades.length; i++) {
midtermGrades[i] = (60 + (double)(Math.random() * 40));
System.out.printf("Student " + studNum++ + " : " + "%.1f\n", midtermGrades[i]);
}

double total = 0;
for (int i = 0; i < midtermGrades.length; i++) {
total += midtermGrades[i];
}

double studAvg = (total / midtermGrades.length);
System.out.printf("The average grade for your class was " + "%.1f\n", studAvg);

int aboveAvg = 0;

for (int i = 0; i < midtermGrades.length; i++) {
if (midtermGrades[i] > studAvg) {
aboveAvg++;
}
}
System.out.println("There are " + aboveAvg + " students in your class who scored above the average.\n");



char[] letterGrades = new char[midtermGrades.length];
for (int i = 0; i < midtermGrades.length; i++) {
letterGrades[i] = (char)midtermGrades[i];

}
}

最佳答案

另一种方法是使用 ASCII 表。例如,96.9的第10位是9,字符AJ的十进制值为65,分别为74。因此,可以用74减去9得到字符A对应的十进制值。以下代码片段展示了如何将 double 数组转换为预期的 char 数组:

代码片段

double[] midtermGrades = {89.6, 73.9, 96.9};
char[] letterGrades = new char[midtermGrades.length];
for (int i = 0; i < midtermGrades.length; i++) {
if (midtermGrades[i] < 60) {
letterGrades[i] = 'E';
} else if (midtermGrades[i] >= 90) {
letterGrades[i] = 'A';
} else {
letterGrades[i] = ((char)('J' - (int)midtermGrades[i]/10));
}
}
System.out.println(Arrays.toString(letterGrades));

控制台输出

[B, C, A]

关于java - 如何在java中从 double 组创建char数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58909211/

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