user2997263
user2997263

Reputation: 9

Printing circle to the screen

Why am I not getting a circle printed to the screen when I run the following block of code? It doesn't print it accurately, seems like something I'm doing wrong when it's scanning the coordinates.

public class Question2 { 

    public static void main(String[] args) { 
        DrawMeACircle(3, 3, 3); // should print to the screen an ellipse looking circle 
    }

    public static void DrawMeACircle(double posX, double posY, double radius) { 

        double xaxis = 20;  // scanning the coordinates
        double yaxis = 20;  // " " 

        for (double x = 0; x < xaxis; x++) { 
            for (double y = 0; y < yaxis; y++) { 

                //using the formula for a cicrle
                double a = Math.abs((posX - x) * (posX - x)); 
                double b = Math.abs((posY - y) * (posY - y)); 

                double c = Math.abs(a + b);        
                double d = Math.abs(radius * radius); 

                // checking if the formula stands correct at each coordinate scanned
                if ( c == d) {
                    System.out.print('#'); 
                } 
                else { 
                    System.out.print(' '); 
                }
            }  
            System.out.println();
        } 
    }
} 

Upvotes: 0

Views: 3865

Answers (1)

I'm afraid that comparing doubles like this

   if ( c == d) {

     System.out.print('#'); 
   } 

is a very unreliable, they're probably missing by a little bit, and you're not printing the circle where you need to.

I'd recommend checking for a range instead

   double arbitraryNumber = 2;
   if ( math.abs(c - d) < arbitraryNumber)) {

     System.out.print('#'); 
   } 

Or, if you want a more reliable way, I'd make a 2-d char array and treat it as a coordinate system, and then fill the 2-d array with the circle and print the array.

You can fill the array with a little bit of trigonometry. Just figure out where the dot should be every few degrees(or radians) until you've gone 360 degrees

Upvotes: 2

Related Questions