我正在尝试创建一个程序,该程序从用户那里获取双倍的值并将它们存储在数组中,然后再将它们分开并舍入答案。但是我一直在尝试创建双数组时遇到错误。
double n = sc.nextDouble();
double a[] = new double[n];
double b[] = new double[n];
double roundedValues[] = new double[n];
for (double i = 0; i < a.length; i++) {
System.out.println("Please enter the values you would like to divide as pairs of two numbers: ");
// Read pair and store it inside i-th position of a and b arrays
System.out.println("Enter first number: ");
a[i] = sc.nextDouble();
System.out.println("Enter second number you would like to divide by: ");
b[i] = sc.nextDouble();
roundedValues[i] = Math.round(a[i] / b[i]);
}
我在声明数组的地方出现错误:
不兼容的类型:从double到int的可能有损转换
答案 0 :(得分:3)
首先,定义为n
的变量double n = sc.nextDouble();
是双精度型。你不能创建一个长度为double的数组,因为那样你可能会得到半个元素。想象一下数组4.5元素长!
将n
定义为其中之一:
int n = sc.nextInt()
或
int n = (int)sc.nextDouble();
其次,i
也是双倍!像这样定义:
for (int i = 0; i < a.length; i++) {
这样编译器知道i
是一个整数,并且不必担心需要在double
索引处检索元素,比如第4.2个元素! (不存在,也不应该存在)
继承固定代码:
int n = sc.nextInt();
double a[] = new double[n];
double b[] = new double[n];
double roundedValues[] = new double[n];
for (int i = 0; i < a.length; i++) {
System.out.println("Please enter the values you would like to divide as pairs of two numbers: ");
// Read pair and store it inside i-th position of a and b arrays
System.out.println("Enter first number: ");
a[i] = sc.nextDouble();
System.out.println("Enter second number you would like to divide by: ");
b[i] = sc.nextDouble();
roundedValues[i] = Math.round(a[i] / b[i]);
}
答案 1 :(得分:1)
a[i] and b[i] expect int type, but you supply double to it
Should be
for (int i = 0; i < a.length; i++) {
和
double n = sc.nextDouble();
should be changed to:
int n = sc.nextInt();