如何从组合框中在Visual Studio 2010 C#中创建IF语句?

时间:2015-11-22 09:46:47

标签: c# visual-studio visual-studio-2010

我在使用Visual Studio 2010在C#中创建if语句时遇到问题。我是一个完全的初学者,我需要帮助。

我创建了一个程序来计算周长和不同形状的区域,我创建了一个组合框用于三角形,正方形,矩形和paralellogram等形状列表。我已经创建了3个形状的代码你可以在下面看到,但是我需要一个单独的三角形代码,对于我希望它一起计算宽度和长度然后除以2的区域。

对于周长我希望它将宽度乘以3来计算周长。我希望你明白我的意思是伙计们。

    private void BtnCalc_Click(object sender, EventArgs e) {
        // Here I am declaring my variables and I am converting my data types.

        double length = Convert.ToDouble(LengthArea.Text);
        double width = Convert.ToDouble(WidthArea.Text);

       //Here I am performing the caluclations for and the perimiter and area.
        double Area = length * width;
        double perimeter = 2 * (length + width);


        //Here I am outputting calculations to labels. 

        AreaAnswer.Text = Convert.ToString(Area);
        AnswerPerimiter.Text = Convert.ToString(perimeter);
    }

1 个答案:

答案 0 :(得分:1)

如果形状对您的计算很重要,那么您需要从组合框中获取它。之后,您应该将area和perimiter的计算移动到单独的方法中。

目前还不清楚你是如何定义你的形状的,但我为此目的做了一个小的枚举。

public enum Shape {
    Square,
    Triangle,
    Parallelogram,
    OtherShapes
}

然后使用形状类型,长度和宽度创建一个计算形状区域的方法。

private double CalculateArea(Shape shape, double length, double width)
{
    switch (shape)
    {
        case Shape.Triangle:
            return (length * width) / 2;
            break;
        case Shape.Square:
        case Shape.Parallelogram:
            return length * width;
            break;
        case Shape.OtherShapes:
            //Calculate accordingly
            break;
    }
    return default(double);
}

为计算perimiter做同样的事。之后,您可以在事件处理程序中为按钮调用这些方法。记得首先从组合框中取出形状。

private void BtnCalc_Click(object sender, EventArgs e)
{
    // Here I am declaring my variables and I am converting my data types.

    double length = Convert.ToDouble(LengthArea.Text);
    double width = Convert.ToDouble(WidthArea.Text);

    Shape shape = Shape.Triangle; // This value should be fetched from your combobox

    //Here I am performing the caluclations for and the perimiter and area.
    double Area = CalculateArea(shape, length, width);
    double perimeter = CalculatePerimiter(shape, length, width);

    //Here I am outputting calculations to labels. 
    string AreaAnswer.Text = Convert.ToString(Area);
    string AnswerPerimiter.Text = Convert.ToString(perimeter);
}
相关问题