[英]How to rewrite and condense in Java
我是 Java 新手,我正在嘗試編寫一個函數,該函數將接受輸入,計算前 4 個頻率,然后輸出輸入和接下來的 4 個頻率(小數點后有 2 個值)。 我目前編寫的代碼正是這樣做的,但是當我提交它進行評分時,它告訴我這是錯誤的。 (我可以運行它來測試它並且它每次都有效)。 有人可以幫助我濃縮我必須更整潔的內容,或者只是指出我正確的方向? 謝謝
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double f0 = scnr.nextDouble();
double r = Math.pow(2, (1.0 / 12.0));
double f1 = f0 * Math.pow(r, 1);
double f2 = f0 * Math.pow(r, 2);
double f3 = f0 * Math.pow(r, 3);
double f4 = f0 * Math.pow(r, 4);
double f5 = f0 * Math.pow(r, 5);
System.out.printf("%.2f", f0);
System.out.print(" ");
System.out.printf("%.2f", f1);
System.out.print(" ");
System.out.printf("%.2f", f2);
System.out.print(" ");
System.out.printf("%.2f", f3);
System.out.print(" ");
System.out.printf("%.2f", f4);
}
}
這是使用數組和 for 循環的完美情況。 由於您有多個相同類型的值,然后對它們進行一些計算,這些計算具有某種類型的模式,您可以使用數組來存儲數字, 並使用 for 循環進行計算。
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double f0 = scnr.nextDouble();
double r = Math.pow(2, (1.0 / 12.0));
int numberCount = 5; // how many numbers you want to keep, in this case its 4 of them
double[] nums = new double[numberCount]; // using an array to store the numbers, instead of multiple separate variables
for (int i = 0; i < nums.length; i++) {
nums[i] = f0 * Math.pow(r, i + 1);
}
System.out.printf("%.2f", f0);
for (int i = 0; i < nums.length; i++) {
System.out.printf(" %.2f", nums[i]);
}
}
}
這樣做的好處是這完全不是硬編碼的,因此您可以通過更改變量numberCount
來擴展或縮小要使用的數字數量,而不是多次復制粘貼您的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.