我如何获得总平均值?

时间:2014-11-26 23:34:44

标签: c#

private void txtFinal_Leave_1(object sender, EventArgs e)
    {
        int prelim;
        int midterm;
        int final;
        decimal average;
        string remarks;

        prelim = int.Parse(txtPrelim.Text);
        midterm = int.Parse(txtMidterm.Text);
        final = int.Parse(txtFinal.Text);

        average = (prelim + midterm + final) / 3;
        txtAverage.Text = average.ToString();

        if (average >= 75)
        {
            remarks = "passed";
        }
        else
        {
            remarks = "failed";
        }
        txtRemarks.Text = remarks;


       // this is the output 83 passed
       // I want to be like this 83.25 passed

    }

2 个答案:

答案 0 :(得分:1)

average = (prelim + midterm + final) / 3.0m;

这将解决您的问题。

Int是整数类型;除以两个整数执行整数除法,即小数部分被截断,因为它不能存储在结果类型中(也是int!)。相比之下,十进制有一个小部分。通过调用Decimal.Divide,您的int参数将隐式转换为Decimal。

您可以通过显式地将至少一个参数强制转换为浮点类型来强制执行int参数的非整数除法,例如:3.0m这将转换为十进制

答案 1 :(得分:-2)

请升级您的代码,如下所示:

average = Convert.ToDecimal(prelim + midterm + final) / 3;
txtAverage.Text = string.Format("{0:0.00}", average);