在 C++ 中画一个圆,而是画一个菱形
Drawing a circle in C++, but drawing a diamond instead
我正在进行一个编码项目,该项目让我们使用星号绘制各种形状。到目前为止,我已经绘制了一个 X、一个矩形以及一个正方形的上部和下部。最终项目让我们画了一个圆,我在之前的 4 个项目中使用了相同的方法——使用嵌套的 for 和 if else 循环创建一种网格,并指定在何处绘制“”或“” *" 不足。这是我的代码:
int main() {
int rad; // int for radius
cout << "We are creating a circle made of asterisks. Please input the radius: " << endl;
cin >> rad;
int i;
int t;
for(i = 1 ; i <= (rad * 2) + 1; i++)
{
for(t = 1; t <= (rad * 2) + 1 ; t++)
{
if((i == 1 && t == rad + 1) /*|| (i == (rad * 2) && t == rad + 1) || (i == rad/2 && t == rad/2)*/)
{
cout << "*";
}
else if (i >= 2 && i <= rad && t == (rad+1) - (i-1))
{
cout << "*";
}
else if (i >= 2 && i <= rad && t == (rad+1) + (i-1))
{
cout << "*";
}
else if (i >= rad && t == (i - rad))
{
cout << "*";
}
else if (i >= rad && t == (rad * 2) + 2 - (i - rad))
{
cout << "*";
}
else
{
cout << " ";
}
}
cout<< endl;
}
return 0;
}
上面的输出?一颗完美的钻石:
We are creating a circle made of asterisks. Please input the radius: 5
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
显然我的方法不起作用。我已经尝试调整我的参数以增加星号的间距,创建一种粗略的圆形近似值,但它看起来并不正确。我忍不住认为必须有一种优雅、优越的方式来做到这一点。也许是一种使用半径的更数学方法。有什么建议或提示吗?
这里有一些关于如何画圆的提示:
这里有一个更数学化的方法,使用半径画圆。
#include <iostream>
#include <math.h>
using namespace std;
int pth (int x,int y) {
return sqrt (pow(x,2)+pow(y,2));
}
int main ( ) {
int c=0;
int r=10;
const int width=r;
const int length=r*1.5;
for (int y=width;y >= -width;y-=2) {
for (int x=-length;x <= length;x++) {
if ((int) pth(x,y)==r) cout << "*";
else cout << " ";
}
cout << "\n";
}
cin.get();
return 0;
}
我正在进行一个编码项目,该项目让我们使用星号绘制各种形状。到目前为止,我已经绘制了一个 X、一个矩形以及一个正方形的上部和下部。最终项目让我们画了一个圆,我在之前的 4 个项目中使用了相同的方法——使用嵌套的 for 和 if else 循环创建一种网格,并指定在何处绘制“”或“” *" 不足。这是我的代码:
int main() {
int rad; // int for radius
cout << "We are creating a circle made of asterisks. Please input the radius: " << endl;
cin >> rad;
int i;
int t;
for(i = 1 ; i <= (rad * 2) + 1; i++)
{
for(t = 1; t <= (rad * 2) + 1 ; t++)
{
if((i == 1 && t == rad + 1) /*|| (i == (rad * 2) && t == rad + 1) || (i == rad/2 && t == rad/2)*/)
{
cout << "*";
}
else if (i >= 2 && i <= rad && t == (rad+1) - (i-1))
{
cout << "*";
}
else if (i >= 2 && i <= rad && t == (rad+1) + (i-1))
{
cout << "*";
}
else if (i >= rad && t == (i - rad))
{
cout << "*";
}
else if (i >= rad && t == (rad * 2) + 2 - (i - rad))
{
cout << "*";
}
else
{
cout << " ";
}
}
cout<< endl;
}
return 0;
}
上面的输出?一颗完美的钻石:
We are creating a circle made of asterisks. Please input the radius: 5
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
显然我的方法不起作用。我已经尝试调整我的参数以增加星号的间距,创建一种粗略的圆形近似值,但它看起来并不正确。我忍不住认为必须有一种优雅、优越的方式来做到这一点。也许是一种使用半径的更数学方法。有什么建议或提示吗?
这里有一些关于如何画圆的提示:
这里有一个更数学化的方法,使用半径画圆。
#include <iostream>
#include <math.h>
using namespace std;
int pth (int x,int y) {
return sqrt (pow(x,2)+pow(y,2));
}
int main ( ) {
int c=0;
int r=10;
const int width=r;
const int length=r*1.5;
for (int y=width;y >= -width;y-=2) {
for (int x=-length;x <= length;x++) {
if ((int) pth(x,y)==r) cout << "*";
else cout << " ";
}
cout << "\n";
}
cin.get();
return 0;
}