用c语言编写koch雪花的代码
时间: 2023-10-20 07:17:37 浏览: 121
以下是用C语言编写Koch雪花的代码:
```c
#include <stdio.h>
#include <math.h>
void koch(int n, double x1, double y1, double x2, double y2)
{
if (n == 0) {
printf("%.2f %.2f\n", x1, y1);
return;
}
double sx = (2 * x1 + x2) / 3;
double sy = (2 * y1 + y2) / 3;
double tx = (x1 + 2 * x2) / 3;
double ty = (y1 + 2 * y2) / 3;
double ux = (tx - sx) * cos(M_PI / 3) - (ty - sy) * sin(M_PI / 3) + sx;
double uy = (tx - sx) * sin(M_PI / 3) + (ty - sy) * cos(M_PI / 3) + sy;
koch(n-1, x1, y1, sx, sy);
koch(n-1, sx, sy, ux, uy);
koch(n-1, ux, uy, tx, ty);
koch(n-1, tx, ty, x2, y2);
}
int main()
{
int n;
scanf("%d", &n);
double x1 = 0, y1 = 0;
double x2 = 100, y2 = 0;
koch(n, x1, y1, x2, y2);
printf("%.2f %.2f\n", x2, y2);
return 0;
}
```
代码实现了Koch雪花的绘制,其中koch函数用来递归地绘制每一层的线段,main函数中读入输入的层数n,然后调用koch函数绘制整个雪花。
阅读全文