我想在 consol 中用 * 画一个矩形。现在我有了绘制矩形周长及其对称轴的代码,但我不知道如何绘制对角线。你能帮助我吗?这是我的代码
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[]) {
int s,d;
printf ("the length of the rectangle \n");
scanf ("%d",&s);
printf ("width of the rectangle \n ");
scanf ("%d",&d);
int l;
int p;
int przekatna;
for (p=1; p<=s; p++)
{
printf ("\n");
for (l=1;l<=d; l++)
{
if(p==1 || l==1 || l==d || s==p || p==((d+1)/2) ) printf("*"); else printf(" ");
if ( l==(d)/2 && p!=((d+1)/2) && p!=1 && p!=s)
printf("*"); else printf("");
}
}
return 0;
}
编辑,它的代码很好,它的工作我的老师向我解释了如何制作对角线,这就是它
#include <stdlib.h>
#include <math.h>
int main() {
int l;
int p;
int s;
int d;
printf ("the length of the rectangle \n");
scanf ("%d",&s);
printf ("width of the rectangle \n ");
scanf ("%d",&d);
for (p=1; p<=s; p++)
{
printf ("\n");
for (l=1;l<=d; l++)
{
if(p==1 || l==1 || l==d || s==p
|| p==s/2 || l==l/2 ||
l==p*round(d/s) || l==(s+1-p)*round(d/s) )
printf("*"); else printf(" ");
}
}
return 0;
}
最佳答案
这实际上根本不是一个小问题!
你看,对角线(当我们将它们想象成与圆周线宽度相同的线时)与整数坐标的对应关系并不好。因此,如果您使用 '*'
字符,要么字符过多(每行多个字符),要么字符太少,在行中出现中断。
您可能想使用 Bresenham's line drawing algorithm对于这个问题。
或者 - 如果你想简单化,每行放置一个 '*'
,使用对角线公式,四舍五入,选择最佳值,而不考虑其他行:
major_diagonal_y = (x - start_x) * ((float) rectangle_y_dim) / rectangle_x_dim
(假设 x 是垂直维度,y 是水平维度;您使用了其他符号,但我发现它们有点困惑。)
对于相反的(次)对角线,使用
minor_diagonal_y = rectangle_y_dim - major_diagonal_y
如果您愿意使用其他字符,可以咨询this tutorial on ASCII art , 有一个关于对角线的部分。它演示了如何改变字符的使用以有效地获得“子字符”分辨率。引用他们的例子:
/ .' _,-' __
/ .' _,-' __..--''
/ .' _,-' __..''
/ .' _,-' __..--''
/ .' _,-' __..--''
/ .' _,-' __..--'' ____....----"""
/ .' _,-' __..--'' ____....----""""
/ .' ,-' __..--'' ____....----""""
关于c++ - 如何在控制台中用 C++ 绘制具有对角线和对称轴的矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50358725/