Hello everyone, I am still fairly a beginner in C++, having only around 5 months of experience. This is actually a 3-part-question-assignment where I am first needed to display a diamond, then a circle (only its circumference) and finally a diamond within the circle.
This is my diamond's code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
int x, y, radius=15;
for (x = -radius; x <= radius; x++)
{
for (y = -radius; y <= radius; y++)
{
cout << ((abs(x) + abs(y) <= radius) ? "*" : " ");
}
cout << endl;
}
return 0;
}
int main()
{
float r = 15;
float y = r;
float x;
float r_in = r - 0.5;
float r_out = r + 0.5;
for (y = r; y >= -r; y--)
{
for (x = -r; x < r_out; x += 0.5)
if (((abs(x - 0.5)*1.395)) + ((abs(y)*0.55)) <= (r_out*0.55)) //Diamond
cout << "*";
else
cout << " ";
float R = x * x + y * y; //Circle
if (R >= r_in * r_in && R <= r_out * r_out)
{
cout << "*";
}
else
{
cout << ' ';
}
}
cout << endl;
}
return 0;
}
(Those seemingly random values at the Diamond code are my attempts to keep the diamond in shape)
The first 2 codes are fine and all, but when it comes to the 3rd code, the circle gets horribly distorted and there's this weird spacing after each "*". I noticed that this happens after I (practically) copy pasted the Diamond code above the Circle's, but I have no idea what's the cause.
I'm sorry that this has turned out to be a lengthy problem, but any hints/advises is greatly appreciated.
// #include <math.h> // C maths header
#include <cmath> // C++ maths header
std::abs has overloads, it can handle floats and doubles as well as integral types :+)
@Loke
Don't use floating point numbers in conditions with loops, they aren't exact so you might get off by one errors despite using relational operators like < . Instead calculate how many times to loop as an int (61 in your case) , then use that value in the loop.