简体   繁体   English

C#:两步文本框计算仅在两次单击“计算”按钮时才产生正确的结果

[英]C#: A two step textbox calculation is only yielding the correct result when clicking my calculate button twice

I understand exactly why this is happening, but I can't figure out how to fix it. 我完全理解为什么会这样,但是我不知道如何解决。 Textbox3 is pulling the initial value of textbox2, not the new calculated value. Textbox3正在提取textbox2的初始值,而不是新的计算值。 This is not a school project, rather a simple calculator for my office for some radio hardware we use. 这不是一个学校项目,而是一个用于我办公室的简单计算器,用于我们使用的某些无线电硬件。 I could fix this by making the button click twice programmatically etc, but I want to know how to fix this the correct way. 我可以通过以编程方式使按钮两次单击来解决此问题,但是我想知道如何正确解决此问题。 My programs are always so simple I get accused of it being "homework" but I can guarantee it is not. 我的程序总是如此简单,以至于我被指责为“作业”,但我可以保证并非如此。 I am sure it is simple as a couple paranthesies missing...Thanks in advance 我敢肯定这很简单,因为缺少几个亲戚关系...预先感谢

    private void button1_Click(object sender, EventArgs e)
    {
        if (double.TryParse(textBox1.Text, out origin)
            && double.TryParse(textBox2.Text, out tb2)
             && double.TryParse(textBox4.Text, out channels))

            textBox2.Text = (30.00 - (10 * Math.Log10(origin))).ToString("n2");
            textBox3.Text = (tb2 - (10 * Math.Log10(channels))).ToString("n2");          

    }

Change the calculation to: 将计算结果更改为:

tb2 = 30.00 - (10 * Math.Log10(origin));
var tb3 = tb2 - (10 * Math.Log10(channels));
textBox2.Text = tb2.ToString("n2");
textBox3.Text = tb3.ToString("n2");

You are assigning tb2 before you change the value in textbox2. 您要先分配tb2,然后再更改textbox2中的值。 You should change the code to: 您应该将代码更改为:

            if (double.TryParse(textBox1.Text, out origin)
         && double.TryParse(textBox4.Text, out channels))
        {
            textBox2.Text = (30.00 - (10 * Math.Log10(origin))).ToString("n2");
            if (double.TryParse(textBox2.Text, out tb2)
            {
                textBox3.Text = (tb2 - (10 * Math.Log10(channels))).ToString("n2");
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM