定义二维数组 输出图形111111 11111 1111 111 11 1
时间: 2023-06-02 07:06:37 浏览: 209
需要定义一个二维数组,然后使用循环语句输出相应的图形。
代码示例:
```
int[][] arr = new int[6][];
for(int i=0; i<arr.length; i++){
arr[i] = new int[6-i];
for(int j=0; j<arr[i].length; j++){
arr[i][j] = 1;
System.out.print(arr[i][j]);
}
System.out.println();
}
```
输出结果:
```
1 1 1 1 1 1
1 1 1 1 1
1 1 1 1
1 1 1
1 1
1
```
相关问题
使用Java二维数组输出下面图形 0 1 2 2 3 4 3 4 5 6 4 5 6 7 8
以下是Java代码:
```
public class Main {
public static void main(String[] args) {
int[][] arr = {{0, 1, 2}, {2, 3, 4}, {3, 4, 5, 6}, {4, 5, 6, 7, 8}}; // 定义二维数组
for (int i = 0; i < arr.length; i++) { // 遍历每一行
for (int j = 0; j < arr[i].length; j++) { // 遍历每一列
System.out.print(arr[i][j] + " "); // 输出数组元素并加上空格
}
}
}
}
```
输出结果为:0 1 2 2 3 4 3 4 5 6 4 5 6 7 8
js应用二维数组的数据绘制图形
你可以使用canvas元素和JavaScript来创建绘图工具,其中二维数组可以用来表示像素数据。下面是一个简单的例子,它绘制了一个简单的黑白图像。
HTML:
```
<canvas id="myCanvas"></canvas>
```
JavaScript:
```
// 获取canvas元素
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 定义一个二维数组来表示像素数据
var pixels = [
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
];
// 定义像素大小和画布大小
var pixelSize = 10;
var canvasWidth = pixelSize * pixels[0].length;
var canvasHeight = pixelSize * pixels.length;
// 设置画布大小
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// 循环遍历像素数组并绘制矩形
for (var i = 0; i < pixels.length; i++) {
for (var j = 0; j < pixels[0].length; j++) {
if (pixels[i][j] === 1) {
ctx.fillRect(j * pixelSize, i * pixelSize, pixelSize, pixelSize);
}
}
}
```
这个例子中,我们首先获取了canvas元素和2D上下文对象。然后,我们定义了一个二维数组来表示像素数据。接下来,我们定义了像素大小和画布大小,并将画布大小设置为canvas元素的宽度和高度。最后,我们循环遍历像素数组,并使用fillRect()方法在画布上绘制矩形来表示像素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)