如何打印某个部门?

时间:2016-01-06 06:36:18

标签: java for-loop math console

我想创建一个程序来打印扇区模式:

public class MySector{
    public static void main(String[] args){
        for(int i=0;i<32;i++){
            for(int j=0;j<32;j++){
                if((i-16)*(i-16)+(j-16)*(j-16)<16*16){
                    if((i-16)<(j-16)*Math.tan(Math.PI/6)){
                        System.out.print("[]");
                    }else{
                        System.out.print("  ");
                    }
                }else{
                    System.out.print("  ");
                }
            }
            System.out.println("");
        }
    }
}

现在我想打印一个30度扇区,在

(i-16)<(j-16)*Math.tan(Math.PI/6)

它只是简化atan((i-16)/(j-16))&lt; Math.PI / 6,但程序似乎没有打印30度的扇区,而是打印出来:

                  [][][][][][][][][][][]                    
              [][][][][][][][][][][][][][][]                
          [][][][][][][][][][][][][][][][][][][]            
        [][][][][][][][][][][][][][][][][][][][][]          
      [][][][][][][][][][][][][][][][][][][][][][][]        
    [][][][][][][][][][][][][][][][][][][][][][][][][]      
  [][][][][][][][][][][][][][][][][][][][][][][][][][][]    
  [][][][][][][][][][][][][][][][][][][][][][][][][][][]    
    [][][][][][][][][][][][][][][][][][][][][][][][][][][]  
        [][][][][][][][][][][][][][][][][][][][][][][][][]  
            [][][][][][][][][][][][][][][][][][][][][][][][]
                [][][][][][][][][][][][][][][][][][][][][][]
                  [][][][][][][][][][][][][][][][][][][][][]
                      [][][][][][][][][][][][][][][][][][][]
                          [][][][][][][][][][][][][][][][][]
                              [][][][][][][][][][][][][][][]
                                [][][][][][][][][][][][][][]
                                    [][][][][][][][][][][][]
                                        [][][][][][][][][][]
                                          [][][][][][][][][]
                                              [][][][][][][]
                                                  [][][][]  
                                                      [][]  

我尝试修改

(i-16)<(j-16)*Math.tan(Math.PI/6)

作为

(j-16)<(i-16)*Math.tan(Math.PI/6)
(16-i)<(16-j)*Math.tan(Math.PI/6)
(16-j)<(16-i)*Math.tan(Math.PI/6)

但仍未打印某个扇区,问题是什么?

1 个答案:

答案 0 :(得分:0)

尝试使用Math.atan2代替Math.tan。我尝试了以下方法,它运作得很好:

private boolean inSector(int x, int y) {
    if ((x - 16) * (x - 16) + (y - 16) * (y - 16) > 16 * 16)
        return false;
    double angle = Math.atan(y - 16, x - 16);
    return (angle >= 0 && angle <= Math.PI / 6);
}