如何将大于0的值相加?

时间:2015-06-12 00:23:16

标签: c#

实际上我添加b1,b2,b3,b4的值并除以B的数量我有(4)

public Media()
    {
        InitializeComponent();
    }

    double b1 = 0;
    double b2 = 0;
    double b3 = 0;
    double b4 = 0;
    double soma = 0;
    double result = 0;


    private void cmdcalc_Click(object sender, EventArgs e)
    {
        b1 = Convert.ToDouble(txtb1.Text);
        b2 = Convert.ToDouble(txtb2.Text);
        b3 = Convert.ToDouble(txtb3.Text);
        b4 = Convert.ToDouble(txtb4.Text);

        soma = b1 + b2 + b3 + b4;
        result = soma / 4;
        lblmedia.Text = result.ToString();
    }

,但是我只需要添加大于0的值并除以大于0的数量

我怎么能做到这一点?

4 个答案:

答案 0 :(得分:1)

我强烈建议采用功能更强大的方法。虽然我不是很喜欢C#,但这是一个划痕:

    Double b1, b2, b3, b4, soma, count, result = 0;

// At some point you set stuff
b1 = 4;
b2 = 5;
b3 = 0;
b4 = 6;

// And at another point
IEnumerable<Double> list = (new List<Double>{b1, b2, b3, b4}).Where(x => x > 0);

soma = list.Sum();
count = list.Count();

result = soma / count;

答案 1 :(得分:0)

为什么不更通用,并允许任意数量的项目? (减少代码行数)

public Media()
{
    InitializeComponent();
}

List<double> b = new List<double>();
double soma = 0;
double result = 0;


private void cmdcalc_Click(object sender, EventArgs e)
{
       // txtb is an array too in this instance
    b.AddRange(txtb.Select(item => Convert.ToDouble(item.Text)));

    IEnumerable<double> relevant = b.Where(item => item > 0);
    soma = relevant.Sum();
    result = soma / relevant.Count();
    lblmedia.Text = result.ToString();
}

答案 2 :(得分:-1)

阅读conditional statements,您可以根据条件(条件)在其中进行计算。

答案 3 :(得分:-1)

int divi = 0;
double sum = 0;
b1 = Convert.ToDouble(txtb1.Text);
if (b1 > 0) { sum +=b1; divi++; }

b2 = Convert.ToDouble(txtb2.Text);
if (b2 > 0) { sum +=b2; divi++; }

b3 = Convert.ToDouble(txtb3.Text);
if (b3 > 0) { sum +=b3; divi++; }

b4 = Convert.ToDouble(txtb4.Text);
if (b4 > 0) { sum +=b4; divi++; }

if (divi > 0)
{ 
    result = sum / divi;
}
lblmedia.Text = result.ToString();