4 回答

TA貢獻1862條經驗 獲得超6個贊
import java.util.Scanner;
public class LabProgram {
/* Define your method here */
public static double drivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon) {
double totalCost = (dollarsPerGallon * drivenMiles / milesPerGallon);
return totalCost;
}
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
double milesPerGallon = scnr.nextDouble();
double dollarsPerGallon = scnr.nextDouble();
double drivenMiles = 1;
System.out.printf("%.2f ", drivingCost(drivenMiles, milesPerGallon, dollarsPerGallon) * 10);
System.out.printf("%.2f ", drivingCost(drivenMiles, milesPerGallon, dollarsPerGallon) * 50);
System.out.printf("%.2f\n", drivingCost(drivenMiles, milesPerGallon, dollarsPerGallon) * 400);
}
}

TA貢獻1817條經驗 獲得超14個贊
driveMiles 除以每加侖英里數,然后乘以每加侖美元,即可得出每英里行駛的汽油價格。注意:在這種情況下,drivenMiles 只需要傳遞給 movingCost。這就是為什么要添加整數 10、50 和 400 來調用。
由于 DrivingCost 按此順序具有milesPerGallon、dollarsPerGallon 和drivenMiles 參數,因此您必須使用相同的參數順序調用該方法。
“%.2f”將得到右邊兩位小數。添加 \n 后將另起一行。
import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double milesPerGallon, double dollarsPerGallon, double drivenMiles) {
// calcuating the cost of gas
double totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon;
return totalCost;
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double milesPerGallon;
double dollarsPerGallon;
milesPerGallon = scnr.nextDouble();
dollarsPerGallon = scnr.nextDouble();
// order of the call to the method is important, printing cost of gas for 10, 50, and 400 miles
System.out.printf("%.2f ",drivingCost(milesPerGallon, dollarsPerGallon, 10));
System.out.printf("%.2f ",drivingCost(milesPerGallon, dollarsPerGallon, 50));
System.out.printf("%.2f\n",drivingCost(milesPerGallon, dollarsPerGallon, 400));
}
}

TA貢獻2011條經驗 獲得超2個贊
import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double milesPerGallon, double dollarsPerGallon, double drivenMiles) {
return (drivenMiles / milesPerGallon) * dollarsPerGallon;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double milesPerGallon, dollarsPerGallon;
milesPerGallon = input.nextDouble();
dollarsPerGallon = input.nextDouble();
System.out.printf("%.2f ", drivingCost(milesPerGallon, dollarsPerGallon, 10));
System.out.printf("%.2f ", drivingCost(milesPerGallon, dollarsPerGallon, 50));
System.out.printf("%.2f\n", drivingCost(milesPerGallon, dollarsPerGallon, 400));
}
}

TA貢獻1895條經驗 獲得超3個贊
您在主函數中調用了scnr.nextDouble();
六次。確保在運行程序時提供六個double類型的參數。目前,您傳遞的參數少于六個,并且scnr.nextDouble();
拋出異常,因為它找不到下一個 double 類型的參數。
添加回答
舉報