编程长方形代码怎么写

时间:2025-01-24 14:14:57 游戏攻略

Python

```python

定义函数,用于打印长方形

def print_rectangle(width, height):

for i in range(height):

for j in range(width):

print("*", end=" ") 使用*号表示长方形的边界

print() 换行

调用函数,打印一个宽度为5,高度为3的长方形

print_rectangle(5, 3)

```

C++

```cpp

include

using namespace std;

int main() {

int width = 5;

int height = 3;

for (int i = 0; i < height; i++) {

for (int j = 0; j < width; j++) {

cout << "* ";

}

cout << endl;

}

return 0;

}

```

Java

```java

public class Rectangle {

private int width;

private int height;

public Rectangle(int width, int height) {

this.width = width;

this.height = height;

}

public void print() {

for (int i = 0; i < height; i++) {

for (int j = 0; j < width; j++) {

System.out.print("* ");

}

System.out.println();

}

}

public static void main(String[] args) {

Rectangle rect = new Rectangle(5, 3);

rect.print();

}

}

```

C

```csharp

using System;

class Rectangle {

public int Width { get; set; }

public int Height { get; set; }

public Rectangle(int width, int height) {

Width = width;

Height = height;

}

public void Print() {

for (int i = 0; i < Height; i++) {

for (int j = 0; j < Width; j++) {

Console.Write("* ");

}

Console.WriteLine();

}

}

public static void Main(string[] args) {

Rectangle rect = new Rectangle(5, 3);

rect.Print();

}

}

```

JavaScript (Node.js)

```javascript

function printRectangle(width, height) {

for (let i = 0; i < height; i++) {

for (let j = 0; j < width; j++) {

process.stdout.write("* ");

}

console.log();

}

}

printRectangle(5, 3);

```

这些示例展示了如何使用不同编程语言创建和打印长方形。你可以根据需要选择合适的编程语言,并根据具体需求进行扩展,例如添加颜色、边框或填充等功能。