Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用C语言返回函数值_C# - Fatal编程技术网

C# 用C语言返回函数值

C# 用C语言返回函数值,c#,C#,我在一个c程序上工作,该程序通过输入姓名、工作时间、小时工资和扣除代码来计算总工资、税收、扣除额和净工资。我有一个特定部分的问题。我无法让我的GrossPay函数返回总工资作为显示在文本框中的金额。该函数将工时和小时工资作为参数,并将其相乘,将结果分配给总工资,然后返回。我对C语法不是很在行,所以我一直在利用互联网作为资源来尝试编写这段代码。这是迄今为止该程序尚未完成的代码 private void btnCalculate_Click(object sender, EventArgs e)

我在一个c程序上工作,该程序通过输入姓名、工作时间、小时工资和扣除代码来计算总工资、税收、扣除额和净工资。我有一个特定部分的问题。我无法让我的GrossPay函数返回总工资作为显示在文本框中的金额。该函数将工时和小时工资作为参数,并将其相乘,将结果分配给总工资,然后返回。我对C语法不是很在行,所以我一直在利用互联网作为资源来尝试编写这段代码。这是迄今为止该程序尚未完成的代码

 private void btnCalculate_Click(object sender, EventArgs e)
    {
        string employeeName = txtEmployeeName.Text;
        decimal hoursWorked = Decimal.Parse(txtHoursWorked.Text);
        decimal hourlyRate = Decimal.Parse(txtHourlyRate.Text);
        int deductionCode = Int32.Parse(txtDeductionCode.Text);
        GrossPay();
    }

    private void GrossPay(decimal hoursWorked, decimal hourlyRate)
    {
        decimal grossPay = hoursWorked * hourlyRate;    
        grossPay = Decimal.Parse(txtGrossPay.Text);
    }

您将返回类型设置为void,这意味着它在完成时不返回任何内容。为了返回某些内容,必须声明要返回的类型。然后,在函数代码到达末尾之前,必须返回某些内容或抛出异常

在本例中,让我们将返回类型设置为decimal,并返回grossPay变量,该变量的类型为decimal。我们也不需要从文本框解析它,因为您通过函数参数传递它

private decimal GrossPay(decimal hoursWorked, decimal hourlyRate)
{
    decimal grossPay = hoursWorked * hourlyRate;    
    return grossPay;
}
我们可以将其缩短,因为不需要grossPay变量

private decimal GrossPay(decimal hoursWorked, decimal hourlyRate)
{
    return hoursWorked * hourlyRate;    
}
由于此函数似乎不依赖任何外部信息,因此最好将其设置为静态函数,这样在调用GrossPay函数之前就不必拥有该类的实例

private static decimal GrossPay(decimal hoursWorked, decimal hourlyRate)
{
    return hoursWorked * hourlyRate;    
}
使其成为静态允许您这样称呼它:

decimal grossPay = MyCalculationUtilities.GrossPay(hoursWorked, hourlyRate);
与此相反:

MyCalculationUtilities calculator = new MyCalculationUtilities();
decimalgrossPay = calculator.GrossPay(hoursWorked, hourlyRate);

最后一个建议是,我建议将它从GrossPay改为CalculateGrossPay,因为它更能描述函数的实际功能。

试试private decimal GrossPay。。。并在最后一次声明中返回grossPay;这里的问题是什么?返回工作小时数*hourlyRate;不需要临时变量