C#代码中的语法语法问题。在代码内创建逻辑错误

时间:2018-11-06 00:47:22

标签: c#

可以使用以下顺序创建pi的值: 4 – 4/3 + 4/5 – 4/7 + 4/9。

编写一个Windows Forms应用程序,该应用程序提示用户输入多个术语,并计算指定数量的术语的序列值。我无法四舍五入得到的价值。

想象一下这是否是设计页面(我正在使用Visual Studio 2017)


输入词条数:[]

[CALCULATE] //这是一个按钮

(*标签2)在[插入文本框输入值]项之后近似pi的值。

(*标签3)[印刷的pi的值]


那么,如何获得文本框的正确输入? 并同时打印两条消息?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void calculateButton_Click(object sender, EventArgs e)
    {
       // Need Variable names for input of textbox. Textbox must be a double value 

        if termsTextBox?
        //termsTextBox is the name of the textbox I named. 

    }

    private void termsTextBox_TextChanged(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Console.WriteLine("Approximate value of pi after" + "" + "terms");
        Console.WriteLine(Math.PI);
    }
}

2 个答案:

答案 0 :(得分:1)

double double; 
string textValue = termsTextBox.Text.Trim(); 
if (textValue != "") 
{ 
    double = Convert.ToDouble(textValue); 
} 

尽管您还应该使用try / catch来确保输入可以实际转换而没有错误。

答案 1 :(得分:1)

解决方案如下:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void termTextBox_TextChanged(object sender, EventArgs e)
    {
        int numberOfTerms;
        if (Int32.TryParse(termTextBox.Text, out numberOfTerms) && numberOfTerms > 0)
        {  
          this.approxLbl.Text = "Approximate the value of pi after " + numberOfTerms + " terms";
          this.calculateBtn.Enabled = true;
        }
        else
        {
            this.approxLbl.Text = "Number of terms must be a positive integer.";
        }
    }

    private void calculateBtn_Click(object sender, EventArgs e)
    {
        //the approximation of pi is given by 4/1 – 4/3 + 4/5 – 4/7 + 4/9 ... number of terms
        double numerator = 4;
        double denominator = 1;

        int numberOfTerms;
        Int32.TryParse(termTextBox.Text, out numberOfTerms);

        double approximation = 0;

        for (int i = 1; i <= numberOfTerms; i++)
        {
            //change the operation each cycle
            if(i % 2 != 0)
            {
                approximation += numerator / denominator;
            }
            else
            {
                approximation -= numerator / denominator;
            }
            denominator += 2;
        }

        this.resultLbl.Text = "The approximation is " + approximation;
    }
}

您的表格应如下所示: enter image description here

结果:enter image description here

希望有帮助