Перевод кода Pascal ABC на язык C# (Рисование архимедовой спирали)
Формулировка задачи:
uses crt,graphABC;
var xc,yc,x,y,k:integer;
r,f:real;
begin
repeat
write('k [5..20] k=');readln(k);
until k in [5..20];
xc:=windowwidth div 2;
yc:=windowheight div 2;
line(0,yc,2*xc,yc);
line(xc,0,xc,2*yc);
f:=0;
while f<=4*pi do//fi>0, правая спираль
begin
r:=k*f;
x:=round(xc+r*cos(f));
y:=round(yc-r*sin(f));
putpixel(x,y,14);
f:=f+0.001;
end;
{while f>=-4*pi do//fi<0, левая спираль
begin
r:=k*f;
x:=round(xc+r*cos(f));
y:=round(yc-r*sin(f));
putpixel(x,y,14);
f:=f-0.001;
end;}
end.Решение задачи: «Перевод кода Pascal ABC на язык C# (Рисование архимедовой спирали)»
textual
Листинг программы
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsForms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox1.Image = new Bitmap(400, 400);
}
private void button1_Click(object sender, EventArgs e)
{
int k;
if (!int.TryParse(textBox1.Text, out k) || k < 5 || k > 20)
{
MessageBox.Show("Введите число от 5 до 20!");
return;
}
var graphics = Graphics.FromImage(pictureBox1.Image);
DrawArhimed(graphics, pictureBox1.Image.Size, k);
pictureBox1.Invalidate();
}
public static void DrawArhimed(Graphics graphics, Size size, int k)
{
const double TWO_PI = 2 * Math.PI;
const double STEP = TWO_PI / 360;
const int COUNT_CIRCULUS = 4;
const int SCALE = 10;
var pen = new Pen(Color.Green);
int centerX = size.Width >> 1, centerY = size.Height >> 1;
graphics.Clear(Color.White);
graphics.DrawLine(pen, 0, centerY, centerX << 1, centerY);
graphics.DrawLine(pen, centerX, 0, centerX, centerY << 1);
int oldX = centerX, oldY = centerY;
for (double i = 0; i < COUNT_CIRCULUS * TWO_PI; i += STEP)
{
var p = SCALE * i / TWO_PI * k;
var x = (int)(p * Math.Cos(i)) + centerX;
var y = (int)(p * Math.Sin(i)) + centerY;
graphics.DrawLine(pen, oldX, oldY, x, y);
oldX = x;
oldY = y;
}
}
}
}