在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;
}
这里有一些关于如何画圆的提示:
- http://www.tutorialspoint.com/computer_graphics/circle_generation_algorithm.htm
- https://en.wikipedia.org/wiki/Midpoint_circle_algorithm
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '