在这个HackerRank挑战中,我需要通过将tip_percent(即meal_cost的20%)和tax_percent(即meal_cost的8%)相加来求出总餐费,meal_cost为12美元。 所以输出必须是15的整数,但我的输出结果是14美元。
它在定制值(比如meal_cost的12.50美元)上似乎确实可以正常工作,后来总计得到的四舍五入值为16美元。 我在这里做错了什么?
static double findMealTotal(double meal_cost, int tip_percent, int tax_percent) {
tip_percent = (int)(meal_cost * tip_percent)/100;
tax_percent = (int)(meal_cost * tax_percent)/100;
return meal_cost + tip_percent + tax_percent;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double meal_cost = scanner.nextDouble();
int tip_percent = scanner.nextInt();
int tax_percent = scanner.nextInt();
//changed solve to mealTotal
double mealTotal = findMealTotal(meal_cost, tip_percent, tax_percent);
System.out.println(Math.round(mealTotal));
scanner.close();
}
您使用的是整数。 整数是四舍五入的,因此在下一次计算时会失去精度。 尝试使用double并在末尾强制转换为int。
static void Main(string[] args)
{
double cost = findMealTotal(12, 20, 8);
Console.WriteLine(cost.ToString());
}
static double findMealTotal(double meal_cost, int tip_percent, int tax_percent)
{
double tip = meal_cost * tip_percent / 100;
double tax = meal_cost * tax_percent / 100;
return meal_cost + tip + tax;
}
并且不要在函数中重用参数。 这是不好的做法。