亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何讓for循環程序只循環20次?

如何讓for循環程序只循環20次?

莫回無 2023-10-19 14:54:40
到目前為止我的計劃:import java.util.Scanner;  public class Temperature {   public static void main(String[] args)   {      int count = 20;      double fahrenheit;      double celsius;      String input;      // Scanner object for keyboard input.      Scanner kb = new Scanner(System.in);      // Get the information.      System.out.print("Enter your starting temperature in Fahrenheit:  ");      fahrenheit = kb.nextDouble();      // Display the results in a table.      System.out.println("Fahrenheit   Celsius");      System.out.println("-----------------------");      for (fahrenheit = fahrenheit; fahrenheit <= count; fahrenheit += 5)      {      // Calculate      celsius = (fahrenheit - 32)*(5.0 / 9.0);      System.out.printf("%,.2f \t\t\t %,.2f\n", fahrenheit, celsius);      }   }}現在我需要它做的是生成一個包含從華氏度到攝氏度的 20 種溫度轉換的表格。如果用戶輸入 0,則輸出的前 3 行示例如下:華氏度:0 攝氏度:-17.78華氏度:5 攝氏度:-15.00華氏度:10 攝氏度:-12.22ETC...問題是,如果輸入超過 20,它就不會循環正確的次數。以下是用戶輸入 5 時會發生的情況的示例:輸出:輸入您的起始華氏溫度:5華氏度 攝氏度5.00 -15.0010.00 -12.2215.00 -9.4420.00 -6.67然后就是輸出結束的地方。有誰知道我怎樣才能使程序顯示 20 F 到 C 的等價物,無論用戶輸入什么?
查看完整描述

3 回答

?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

你的for循環一團糟:for (fahrenheit = fahrenheit; fahrenheit <= count; fahrenheit += 5)它正在將溫度與計數(fahrenheit <= count)進行比較。


如果你總是想要 20 步,那么:


for (int i = 0; i < count; i++) {

    ...

    fahrenheit  += 5;

}

會做的。


查看完整回答
反對 回復 2023-10-19
?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

選項1,添加一個計數器并使用它。


for (int i = 0; i < count; i++, fahrenheit += 5)

{

    // Calculate

    celsius = (fahrenheit - 32)*(5.0 / 9.0);

    System.out.printf("%,.2f \t\t\t %,.2f\n", fahrenheit, celsius);

}

count選項 2,在循環時遞減(并測試零)。


for (; count > 0; count--, fahrenheit += 5)

{

    // Calculate

    celsius = (fahrenheit - 32)*(5.0 / 9.0);

    System.out.printf("%,.2f \t\t\t %,.2f\n", fahrenheit, celsius);

}


查看完整回答
反對 回復 2023-10-19
?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

您需要做的是保持一個index從 0 開始一直到 20 的單獨變量。這意味著每次都會更改 2 個變量index和fahrenheit,并且 for 循環將如下所示:


int index = 0

for (fahrenheit = fahrenheit; index < count; fahrenheit += 5) {

    ...

    index++;

}


查看完整回答
反對 回復 2023-10-19
  • 3 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號