主要为第一维和第二维分配2个随机数(在3到10之间)
我有这个,但Math.random()方法不起作用
import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
double doubMatrix1[][] = (int) (Math.random()*(10-3+1)+3);
double doubMatrix2[][];
double doubMatrix3[][];
}
}
答案 0 :(得分:0)
要在Java中创建多维数组,请使用new <type>[dim1][dim2]
,如下面的代码所示:
Random rand = new Random();
int r1 = rand.nextInt(8) + 3;
int r2 = rand.nextInt(8) + 3;
double doubMatrix[][] = new double[r1][r2];
答案 1 :(得分:0)
您的代码中的问题是您尝试使用int
初始化double矩阵类型必须等于!
以下是您修复的代码。
import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
int d1 = (int) (Math.random()*(10-3+1)+3);
int d2 = (int) (Math.random()*(10-3+1)+3);
double doubMatrix1[][] = new double[d1][d2];
double doubMatrix2[][];
double doubMatrix3[][];
}
}
希望这个帮助
答案 2 :(得分:0)
Math.random()
返回0.0到1.0之间的分数。因此,对于(int) (Math.random()*(10-3+1)+3)
,您只能得到3到10之间的一个随机数。但是您要将其分配给double doubMatrix1[][]
。所以可能你是以错误的方式调用构造函数。您应该根据教师讲授的方法生成两个不同的随机数r1, r2
,然后调用类似double doubMatrix1[][] = double[r1][r2]
的构造函数
答案 3 :(得分:0)
检查一下,这可能会有所帮助:
// DMA of 2D array in C++
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int x = 3, y = 3;
int **ptr = new int *[x];
for(int i = 0; i<y; i++)
{
ptr[i] = new int[y];
}
srand(time(0));
for(int j = 0; j<x; j++)
{
for(int k = 0; k<y; k++)
{
int a = rand()%5;
ptr[j][k] = a;
cout<<ptr[j][k]<<" ";
}
cout<<endl;
}
}
我们使用指针并像处理2D数组一样处理它,使用%作为限制