背景:
我已经成功编写了可以生成从0到2pi的正弦波的代码。通过调整常量xPrecision
和yPrecision
,您可以在水平或垂直方向上拉伸图形。
当 xPrecision = yPrecision = 10
时,我获得了这个漂亮的输出(在Eclipse中):
我的问题:
现在我希望显示数字0到9,而不是星号。因此,最左侧的星号将被替换为0,第二个左起的星号将被替换为1,以此类推。当您达到9时,下一个数字再次变为零。
我不知道如何做到这一点。我看过像这样的波形模式,但它们是固定宽度的模式,而我的模式是可伸缩的。
我唯一能想到的方法是将输出转换为二维字符数组,然后从左到右手动刮掉*
,将其替换为数字,然后打印它。然而,在较大的 x/yPrecision
值下,这会极大地消耗内存。
实现此输出的最优方法是什么?
输出正弦波的代码:
class sine {
static final double xPrecision = 10.0; // (1/xPrecision) is the precision on x-values
static final double yPrecision = 10.0; // (1/yPrecision) is the precision on y-values
static final int PI = (int) (3.1415 * xPrecision);
static final int TPI = 2 * PI; // twice PI
static final int HPI = PI / 2; // half PI
public static void main(String[] args) {
double xd;
for(int start = (int) (1 * yPrecision), y = start; y >= -start; y--){
double x0 = Math.asin(y / yPrecision),
x1 = bringXValueWithinPrecision(x0),
x2 = bringXValueWithinPrecision(x0 + TPI / xPrecision),
x3 = bringXValueWithinPrecision(PI/xPrecision - x0);
// for debug
//System.out.println(y + " " + x0 + " " + x1 + " " + x2 + " " + x3);
for(int x = 0; x <= TPI; x++){
xd = (x / xPrecision);
if(x1 == xd || x2 == xd || x3 == xd)
System.out.print("*");
else System.out.print(" ");
}
System.out.println();
}
}
public static double bringXValueWithinPrecision(double num){
// obviously num has 16 floating points
// we need to get num within our precision
return Math.round(num * xPrecision) / xPrecision;
}
}
**
处,也就是两个星号相连的地方,就代表着你已经拥有了整个正弦波对吗?第一部分(共 4 部分)/
,你需要将其反转成\\
来得到第二部分,然后再将/\\
反转成\\/
来得到下半部分。(评论中似乎 \ 字符存在缺陷) - Adelin\\\
) - Gaurang Tandon