【问题标题】:Output is incorrect can you nest if statement into loops for array calculation? [closed]输出不正确您可以将 if 语句嵌套到循环中以进行数组计算吗? [关闭]
【发布时间】:2017-11-14 19:14:38
【问题描述】:

这里是完整的源代码它没有输出正确的人,使最多和最少。我最好的猜测是循环内的 if 语句,如果该人工作超过 40 小时,则计算工资。代码很简单,学习 C#。解决此问题的最佳方法是什么....抱歉,我知道这可能是我缺少的一个简单问题。对标签的评论

{
class Program
{
    const double FEDERAL_TAX_DEDUCTION = .10; //Federal Tax 10% of Gross Income
    const double STATE_TAX_DEDUCTION = .05;   //State Tax 5% of Gross Income
    const int    HOURS_OVERTIME = 40;         //# of Hours Needed For Overtime Pay Rate
    const double OVERTIME_PAY_DIFF = 1.5;     //150% of Normal Pay

    static void Main(string[] args)
    {
        int MAX_LIST_VALUE;  //How Many Workers There Are For Array Limit.

        Write("How Many Workers Are Currently Working? ");                  //Asks For User Input # Of Workers
        MAX_LIST_VALUE = Convert.ToInt32(ReadLine());

        string[] workerName = new string[MAX_LIST_VALUE];          
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.Blue;
            WriteLine("Please Enter The Worker's Name: ");        //Asks For User Input For Worker's Names
            workerName[i] = ReadLine();  
        }
        double[] workerWages = new double[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.DarkYellow;
            WriteLine("Please Enter " + workerName[i] + "'s Hourly Wage: "); //Asks For User Input For Worker's Wage
            workerWages[i] = Convert.ToDouble(ReadLine());
        }
        double[] workerWeeklyHours = new double[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.DarkCyan;
            Write("How Many Hours Has {0} Worked This Week? ", workerName[i]); //Asks For User Input For Hours Worked
            workerWeeklyHours[i] = Convert.ToDouble(ReadLine());
        }
        double[] workersRegularPay = new double[MAX_LIST_VALUE];
        double[] workerGrossIncome = new double[MAX_LIST_VALUE];
        double[] workerStateTaxAmount = new double[MAX_LIST_VALUE];                //All Calculation Arrays
        double[] workerFederalTaxAmount = new double[MAX_LIST_VALUE];
        double[] workerNetIncome = new double[MAX_LIST_VALUE];
        double[] workerOvertimeHours = new double[MAX_LIST_VALUE];
        double[] workerOvertimePay = new double[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            if (workerWeeklyHours[i] > HOURS_OVERTIME)                                                    //If Hours # is > 40.
            {
                workerOvertimeHours[i] = workerWeeklyHours[i] - HOURS_OVERTIME;
                workerOvertimePay[i] = workerOvertimeHours[i] * (workerWages[i] * OVERTIME_PAY_DIFF);
                workerGrossIncome[i] = workerOvertimePay[i] + workersRegularPay[i];                   
            }
            else
            {
                workersRegularPay[i] = workerWeeklyHours[i] * workerWages[i];
                workerGrossIncome[i] = workerWeeklyHours[i] * workerWages[i];
                workerStateTaxAmount[i] = workerGrossIncome[i] * STATE_TAX_DEDUCTION;
                workerFederalTaxAmount[i] = workerGrossIncome[i] * FEDERAL_TAX_DEDUCTION;
                workerNetIncome[i] = workerGrossIncome[i] - workerFederalTaxAmount[i] - workerStateTaxAmount[i];
                workerOvertimePay[i] = 0;
                workerOvertimeHours[i] = 0;
            }
        }
        ForegroundColor = ConsoleColor.Blue;
        WriteLine("\nNAMES ARE BLUE.");
        ForegroundColor = ConsoleColor.DarkYellow;
        WriteLine("HOURLY WAGES ARE DARK YELLOW.");
        ForegroundColor = ConsoleColor.DarkCyan;
        WriteLine("HOURS WORKED ARE DARK CYAN.");
        ForegroundColor = ConsoleColor.Green;
        WriteLine("NET INCOMES ARE GREEN.");
        ForegroundColor = ConsoleColor.Red;
        WriteLine("-----------------------------");
        WriteLine("There Are " + MAX_LIST_VALUE + " Workers!");  //Echo Of All Data Entered & Calculated For Workers
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.Blue;
            WriteLine("\nWorker's Name: " + workerName[i]);
            WriteLine("-----------------------------");
            ForegroundColor = ConsoleColor.DarkYellow;
            WriteLine(workerName[i] + "'s Hourly Wage: " + workerWages[i].ToString("C"));
            ForegroundColor = ConsoleColor.DarkCyan;
            WriteLine(workerName[i] + "'s Hours Worked This Week: " + workerWeeklyHours[i]);
            ForegroundColor = ConsoleColor.White;
            WriteLine(workerName[i] + "'s Regular Pay: " + workersRegularPay[i].ToString("C"));
            WriteLine(workerName[i] + "'s Gross Income Pay: " + workerGrossIncome[i].ToString("C"));
            WriteLine(workerName[i] + "'s State Tax Amount: " + workerStateTaxAmount[i].ToString("C"));
            WriteLine(workerName[i] + "'s Federal Tax Amount: " + workerFederalTaxAmount[i].ToString("C"));
            ForegroundColor = ConsoleColor.Green;
            WriteLine(workerName[i] + "'s Net Income: " + workerNetIncome[i].ToString("C"));
            WriteLine(workerName[i] + "'s Overtime Hours: " + workerOvertimeHours[i]);
            WriteLine(workerName[i] + "'s Overtime Pay (if any): " + workerOvertimePay[i].ToString("C"));
        }
        ForegroundColor = ConsoleColor.Red;
        WriteLine("\nPress Enter To Continue For The Worker's That Earned The Least & The Most.");
        ReadLine();

        int minIndex = 0;
        string workerLeast = "null";
        double workerRegularPayLeast = 0,
               workerGrossIncomeLeast = 0,
               workerOverTimeLeast = 0;
        int maxIndex = 0;
        string workerMost = "null";
        double workerRegularPayMost = 0,
               workerGrossIncomeMost = 0,
               workerOverTimeMost = 0;

        for (int i = 0; i < workerGrossIncome.Length; i++)         //Calculation For Worker That Made The LEAST
            if (workerGrossIncome[i] < workerGrossIncome[minIndex])
            {
                minIndex = i;
                workerLeast = workerName[i];
                workerRegularPayLeast = workersRegularPay[i];
                workerGrossIncomeLeast = workerGrossIncome[i];
                workerOverTimeLeast = workerOvertimePay[i];
            }
        for (int i = 0; i < workerGrossIncome.Length; i++)         //Calculation For Worker That Made The MOST
            if (workerGrossIncome[i] >= workerGrossIncome[maxIndex])
            {
                maxIndex = i;
                workerMost = workerName[i];
                workerRegularPayMost = workersRegularPay[i];
                workerGrossIncomeMost = workerGrossIncome[i];
                workerOverTimeLeast = workerOvertimePay[i];
            }
        ForegroundColor = ConsoleColor.Green;  
        WriteLine("\nThe Worker That Earned The Least Is {0}.", workerLeast);
        WriteLine("-----------------------------");
        ForegroundColor = ConsoleColor.Magenta;
        WriteLine("{0}'s Gross Income Was {1}.", workerLeast, workerGrossIncomeLeast.ToString("C"));
        WriteLine("{0}'s Regular Pay Was {1}.", workerLeast, workerRegularPayLeast.ToString("C")); //Output For LEAST
        WriteLine("{0}'s Overtime Pay Was {1}.", workerLeast, workerOverTimeLeast.ToString("C"));
        ForegroundColor = ConsoleColor.Cyan;
        WriteLine("\nThe Worker That Earned The Most Is {0}.", workerMost);
        WriteLine("-----------------------------");
        ForegroundColor = ConsoleColor.DarkGray;
        WriteLine("{0}'s Gross Income Was {1}.", workerMost, workerGrossIncomeMost.ToString("C"));
        WriteLine("{0}'s Regular Pay Was {1}.", workerMost, workerRegularPayMost.ToString("C"));   //Output For MOST
        WriteLine("{0}'s Overtime Pay Was {1}.", workerMost, workerOverTimeMost.ToString("C"));
        ForegroundColor = ConsoleColor.Red;
        WriteLine("\nPress Enter To Exit! \nThank You!");
        ReadLine();
    }
}

这就是我认为问题所在..

for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            if (workerWeeklyHours[i] > HOURS_OVERTIME)                                                    //If Hours # is > 40.
            {
                workerOvertimeHours[i] = workerWeeklyHours[i] - HOURS_OVERTIME;
                workerOvertimePay[i] = workerOvertimeHours[i] * (workerWages[i] * OVERTIME_PAY_DIFF);
                workerGrossIncome[i] = workerOvertimePay[i] + workersRegularPay[i];                   
            }
            else
            {
                workersRegularPay[i] = workerWeeklyHours[i] * workerWages[i];
                workerGrossIncome[i] = workerWeeklyHours[i] * workerWages[i];
                workerStateTaxAmount[i] = workerGrossIncome[i] * STATE_TAX_DEDUCTION;
                workerFederalTaxAmount[i] = workerGrossIncome[i] * FEDERAL_TAX_DEDUCTION;
                workerNetIncome[i] = workerGrossIncome[i] - workerFederalTaxAmount[i] - workerStateTaxAmount[i];
                workerOvertimePay[i] = 0;
                workerOvertimeHours[i] = 0;
            }

逻辑问题 输出为:Output end only missing console inputs and first output

【问题讨论】:

  • 您需要先创建一个Minimal, Complete, Verifiable example,然后任何人都可以帮助您
  • 调试您的代码以确定问题的根源。请参阅:Navigating through Code with the Debugger。此外,使用包含 10 个属性的类类型的单个数组比使用 10 个数组要容易得多。
  • 您的问题出在 if 块中,您在其中计算变量 workersRegularPay 和以下变量。当工人有加班时间时,您不计算正常时间。如果工人有加班时间,也应该计算 else 块。

标签: c# arrays output


【解决方案1】:

在您的代码中,如果工人有加班时间,GrossIncome 的计算方式会有所不同。在加班的情况下,计算是错误的,因为使用了一个未初始化的变量 workersRegularPay[i] 并且根本不执行 else 块,从而使工人的加班时间和数据不完整

您应该将计算变量 workerGrossIncome 的循环更改为此

for (int i = 0; i < MAX_LIST_VALUE; i++)
{
    // Calculate the overtime hours and pay (if any) for the current (i) worker
    if (workerWeeklyHours[i] > HOURS_OVERTIME)
    {
        workerOvertimeHours[i] = workerWeeklyHours[i] - HOURS_OVERTIME;
        workerOvertimePay[i] = workerOvertimeHours[i] * (workerWages[i] * OVERTIME_PAY_DIFF);
    }

    // Calculate the regular pay for the same worker 
    // but without the overtime hours
    workersRegularPay[i] = (workerWeeklyHours[i] - workerOvertimeHours[i]) * workerWages[i];

    // Now you could sum the regular pay and the overtime pay 
    workerGrossIncome[i] = workerOvertimePay[i] + workersRegularPay[i];

    // Other calcs to do for the same worker.
    workerStateTaxAmount[i] = workerGrossIncome[i] * STATE_TAX_DEDUCTION;
    workerFederalTaxAmount[i] = workerGrossIncome[i] * FEDERAL_TAX_DEDUCTION;
    workerNetIncome[i] = workerGrossIncome[i] - workerFederalTaxAmount[i] - workerStateTaxAmount[i];
}

【讨论】:

  • 谢谢!现在更有意义了,我知道如果他们加班,这与正常工资的计算“搞砸”有关。 40小时以下计算罚款。再次感谢您的帮助。
【解决方案2】:

C# 是一种面向对象的编程语言。您需要创建一个类来封装所有这些数据并理解它。拥有所有这些松散相关的数组是一团糟——你的代码不可重用,如果工人得到加薪或不同的时间表,数据就不能轻易更改,坦率地说,查看和输入数据会让人困惑。

最好像这样创建一个 Worker 类(在解决方案资源管理器中右键单击您的项目,单击添加,单击类以创建一个新的类文件并将其命名为“Worker.cs”):

public class Worker
{
    // properties contain data for each worker
    public string Name { get; set; }
    public decimal HoursPerWeek { get; set; }
    public decimal HourlyPay { get; set; }

    // this is your constructor.  Set your variables to initial values here
    public Worker(string WorkerName, decimal WorkerHoursPerWeek, decimal WorkerHourlyPay)
    {
        this.Name = WorkerName;
        this.HoursPerWeek = WorkerHoursPerWeek;
        this.HourlyPay = WorkerHourlyPay;
    }

    // use methods to return any calculated values
    public decimal GetWeeklyPay()
    {
        decimal NormalHours;

        if (HoursPerWeek <= 40.0)
            NormalHours = HoursPerWeek;
        else
            NormalHours = 40.0M;

        decimal OverTimeHours;

        if (HoursPerWeek <= 40.0)
            OverTimeHours = 0.0M;
        else
            OverTimeHours = HoursPerWeek - 40.0;

        // hourly pay up to 40 hours, 1.5 times hourly pay for overtime
        return (NormalHours * HourlyPay) + (1.5M * (OverTimeHours * HourlyPay));
    }
}

现在你有了你的工人类,而不是填充一打令人困惑的数组,你只需编写一个程序来创建你的工人类的实例,如下所示:

// in your Program.cs, create instances of your worker class like this:
List<Worker> workers = new List<Worker>();

for (int i = 0; i < MAX_LIST_VALUE; i++)
{
    Console.WriteLine("Enter name for employee:");
    string name = Console.ReadLine();

    Console.WriteLine("Enter hours per week:");
    decimal hours = Decimal.Parse(Console.ReadLine());

    Console.WriteLine("Enter hourly wage:");
    decimal wage = Decimal.Parse(Console.ReadLine());

    // this creates an instance of your worker class and adds it to the list
    workers.Add(new Worker(name, hours, wage));
}

// now you have a list of workers that you can sort using Linq or some other method:
var sortedWorkers = workers.OrderByDescending(w => w.GetWeeklyPay());

// and you can output them in order from most pay to least:
foreach (Worker w in sortedWorkers)
{
    Console.WriteLine("Worker " + w.Name + " makes " + w.GetWeeklyPay().ToString() + " dollars per week!");
}

【讨论】:

  • 我同意使用类会更简单。
猜你喜欢
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多