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 类型的参数。
添加回答
举报