gpt4 book ai didi

java - 数组中的舍入单元格同时仍显示其未舍入副本的问题

转载 作者:行者123 更新时间:2023-12-02 03:29:04 25 4
gpt4 key购买 nike

这是一个计算小费的程序。我需要让 hoursArray[] 正常舍入每个单元格(据我所知,使用 Math.round() 是最好的方法)。问题是我仍然需要将 UNrounded hoursArray[] 存储到totalHours[]中。

期望输出示例:Bob 工作 33.49 小时,Sara 工作 33.5 小时,本周小费为 200.00 美元

因此,Bob 的工作时间应向下舍入为 33,而 Sara 的工作时间应向上舍入为 34。您将能够看到小费收入的差异,Sara 的工作时间多于 Bob。该周仍将显示为 66.99。

现在这个程序做了它应该做的所有其他事情,我只是不知道如何舍入hoursArray[]的每个单元格并仍然保留totalHours []完好无损。

如何对 hoursArray[] 中的每个单元格进行舍入,同时仍将未舍入的值存储到totalHours[] 中?我是否使用hoursArray 的clone()?数组复制()?我被困住了...

问题区域已标记,位于第 33 行和第 43 行之间。 Math.floor() 是必要的,因为我需要程序将小数向下舍入。

import java.util.Arrays;
import java.util.Scanner;

class Tips_Calculation2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
float totalTips = 0;
float totalHours = 0;

System.out.print("How many employees worked for the week?: ");
int numberOfEmps = scan.nextInt();


System.out.println("\nEnter the names of all " + numberOfEmps + " employees");


String[] namesArray = new String[numberOfEmps];
for(int i = 0; i < numberOfEmps; i++)
{
namesArray[i] = scan.next();
}


System.out.println("\nEnter the amount of hours each person worked for the week: ");






//////////////////////////////////////////////////////**THIS IS WHERE IM STUCK**///////////////
int counter = 0;
float[] hoursArray = new float[namesArray.length];
for(int n = 0; n < namesArray.length; n++)
{
System.out.print(namesArray[n] + ": ");
hoursArray[n] = scan.nextFloat();
totalHours = totalHours + hoursArray[n];
counter++;
}
//////////////////////////////////////////////////////////////////////////////////






System.out.println("\nTotal hours: " + totalHours);
System.out.print("\nEnter the amount of money to be distributed as tips: $");
totalTips = scan.nextFloat();
System.out.println("---- OUTPUT ----");
System.out.println();


int x = 0;
for(int a = 0; a < namesArray.length; a++)
{
System.out.println(namesArray[a] + ": " + "$" + Math.floor(((hoursArray[x]/totalHours) * totalTips)));
x++;
System.out.println();
}
}
}

最佳答案

您标记的部分看起来没问题:hoursArray 确实包含每个人工作的小时数(未四舍五入)。

当你进行四舍五入时,你的问题就会出现。从您的描述中,我了解到您想要四舍五入小时数,而不是结果小费。因此,您的计算需要类似于:

Math.round(hoursArray[x]) * totalTips / totalHours

此外,当您计算总小时数时,您需要添加四舍五入的小时数,否则您的小费加起来将达不到所需的总数:

totalHours = totalHours + Math.round(hoursArray[n]);

关于java - 数组中的舍入单元格同时仍显示其未舍入副本的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38349017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com