C++控制台应用程序——画三角形、圆、直线、矩形
时间: 2023-09-17 20:12:15 浏览: 96
下面是一个简单的 C++ 控制台应用程序,用于绘制三角形、圆、直线和矩形:
```c++
#include <iostream>
#include <cmath>
using namespace std;
void drawLine(int x1, int y1, int x2, int y2) {
int dx = abs(x2 - x1), dy = abs(y2 - y1);
int sx = x1 < x2 ? 1 : -1, sy = y1 < y2 ? 1 : -1;
int err = dx - dy;
while (x1 != x2 || y1 != y2) {
cout << ".";
int e2 = 2 * err;
if (e2 > -dy) { err -= dy; x1 += sx; }
if (e2 < dx) { err += dx; y1 += sy; }
}
cout << endl;
}
void drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
drawLine(x1, y1, x2, y2);
drawLine(x2, y2, x3, y3);
drawLine(x3, y3, x1, y1);
}
void drawCircle(int xc, int yc, int r) {
int x = 0, y = r;
int d = 3 - 2 * r;
while (x <= y) {
cout << ".";
if (d < 0) { d += 4 * x + 6; }
else { d += 4 * (x - y) + 10; y--; }
x++;
}
cout << endl;
}
void drawRectangle(int x, int y, int w, int h) {
drawLine(x, y, x + w, y);
drawLine(x + w, y, x + w, y + h);
drawLine(x + w, y + h, x, y + h);
drawLine(x, y + h, x, y);
}
int main() {
// 绘制三角形
cout << "Triangle:" << endl;
drawTriangle(10, 10, 20, 30, 30, 10);
// 绘制圆形
cout << "Circle:" << endl;
drawCircle(20, 20, 10);
// 绘制直线
cout << "Line:" << endl;
drawLine(10, 30, 30, 10);
// 绘制矩形
cout << "Rectangle:" << endl;
drawRectangle(40, 10, 20, 30);
return 0;
}
```
这个程序使用了一些基本的绘图算法,包括绘制直线的 Bresenham 算法、绘制圆形的中点画圆算法、以及绘制矩形的基于直线的算法。你可以根据需要进行修改和扩展。
相关推荐
![](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)
![](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)