簡體   English   中英

為什么沒有可變印刷?

[英]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必須在-11之間,並且如果它的倍數0.50.6等),則它必須在十分之幾。 。 因此,假設X0.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM