[英]Why isn't my variable printing?
public class FirstofTen
{
public static void main(String[] args) throws IOException
{
int i = 10;
while (i >= -10) {
double x = i / 10.0;
i--;
String X = String.format("%.2f", x);
System.out.println(X);
}
i = 10;
while(i >= -10) {
double x = i / 10.0;
i--;
String X = String.format("%.2f", x);
double Y = Math.sqrt(Math.pow(1, 2) - Math.pow(x, 2));
System.out.println(String.format("%.2f", Y));
}
这是学校的作业,我不想要答案,只是帮助。 基本上,我知道三角形的斜边始终为1。我也知道X
必须在-1
和1
之间,并且如果它的倍数0.5
( 0.6
等),则它必须在十分之几。 。 因此,假设X
为0.9
,那么我必须让Java使用勾股定理来计算三角形第三边的结果。 我有那部分。 问题是,我依赖输出。 我得到以下输出:
1.00
0.90
0.80
0.70
0.60
0.50
0.40
0.30
0.20
0.10
0.00
-0.10
-0.20
-0.30
-0.40
-0.50
-0.60
-0.70
-0.80
-0.90
-1.00
0.0
0.44
0.60
0.71
0.80
0.87
0.92
0.95
0.98
0.99
1.00
0.99
0.98
0.95
0.92
0.87
0.80
0.71
0.60
0.44
0.00
如您所见,它先打印X,然后在其正下方打印Y。 如何将它们分为不同的列?
您必须在System.out.println();
指定要打印的内容System.out.println();
相反: System.out.println(Y);
您的第二个while循环将不会输入,因为在第一个while循环之后i
小于-10。 您应该在第二个循环之前重置其值。
您的代码有多个问题:
首先,在第二个循环开始时,您大声将i
重置为十; 或使用for
循环,会更清洁。 这样,这段代码
int i = 10;
while (i >= -10) {
// work
i--;
}
变成这个:
for (int i = 10; i >=-10; i--) {
// work
}
其次,在第二个循环中,应格式化Y
并实际打印出来。 您也可以一口气进行格式化和打印:
System.out.println(String.format("%.2f", Y));
while (i >= -10){
double x = i / 10.0;
i--;
String X = String.format("%.2f", x);
System.out.println("X : " + X);
}
当while循环退出时, i的值是i = -1.0
因此,由于i> = -10返回false ,因此下一个while不执行
解决方案:
int i=10;
System.out.print("Values For X : ");
while (i >= -10) {
// Code Goes Here for first while loop
System.out.print(" " + X)
}
i=10; // Just re-initialize i with previous value i.e., 10
System.out.print("Values For Y : ");
while(i>=-10) {
// Code Goes Here for second while loop
System.out.print(" " + Y); // and not System.out.println();
}
在第二次while循环之前在代码中再次初始化i = 10它将起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.