I would like to know the error in my code. My goal is to draw a horizontal ellipse on the screen.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void ellipse(){
int x,y;
int center = 30;
int centery = 30;
for (y=0; y<center; y++) {
for (x=0; x<center; x++) {
if((pow((x-center),2.0)/100) + ((pow((y-centery),2.0)/25))< 1)
printf("*");
else
printf(" ");
}
printf("\n");
}
}
void main(){
ellipse();
return 0;
}
But this is all I get in the console :
************
***************
******************
*******************
but i want this (but horizontal) and without the center :
*
*************
*****************
*********************
*************************
***************************
*****************************
*******************************
*********************************
*********************************
***********************************
***********************************
*************************************
*************************************
***************************************
***************************************
***************************************
***************************************
***************************************
***************************************
*****************************************
***************************************
***************************************
***************************************
***************************************
***************************************
***************************************
*************************************
*************************************
***********************************
***********************************
*********************************
*********************************
*******************************
*****************************
***************************
*************************
*********************
*****************
*************
*
#include <stdio.h>
void ellipse(double a, double b, int centerx, int centery)
{
double a_sq = a * a;
double b_sq = b * b;
for (int y = 0; y <= centery + b; y++)
{
for (int x = 0; x <= centerx + a; x++)
{
double result = ((x - centerx) * (x - centerx)) / a_sq
+ ((y - centery) * (y - centery)) / b_sq;
if (result <= 1.0)
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
int main()
{
ellipse(10.0, 5.0, 10, 10);
}
I changed the following:
Accepted length of semi-major and semi-minor axis along with center coordinates as function parameters.
Used type double
for calculations.
Changed the loop conditions - you were using center
for for x and y. I changed it so that x goes from 0
to centerx + a
and y goes from 0
to centery + b
.
I checked for <= 1.0
instead of < 1
as points on the perimeter of ellipse will have value = 1.
Removed unnecessary headers.
Seems to work fine here.