繁体   English   中英

我如何告诉我的程序它应该继续从数字中减去?

[英]How do I tell the my Program that it should keep subtracting from a number?

我有以下代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    double salaryAmount;
    double subtractAmount;
    double newSalaryAmount;
    string amountBackToString;

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            salaryAmount = double.Parse(TextBox1.Text);
            label1.Content = salaryAmount.ToString();
        }
        catch (Exception)
        {

            MessageBox.Show("This was not a valid input.");
        } 
    }

    private void Button2_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            subtractAmount = double.Parse(TextBox2.Text);
            newSalaryAmount = salaryAmount - subtractAmount;
            label1.Content = newSalaryAmount.ToString();
        }
        catch (Exception)
        {
            MessageBox.Show("This was not a valid input.");
        }
    }

    private void Button3_Click(object sender, RoutedEventArgs e)
    {
        amountBackToString = Convert.ToString(newSalaryAmount);
        string[] currentAmount = { amountBackToString };
        File.WriteAllLines(@"C:\Users\Silas\Downloads\Lohn.txt", currentAmount);
    }

    private void Button4_Click(object sender, RoutedEventArgs e)
    {
        string text = File.ReadAllText(@"C:\Users\Silas\Downloads\Lohn.txt");
        label1.Content = text;
        salaryAmount = Convert.ToDouble(label1.Content);
    }
}

问题是它每次都会将数字重置为初始输入,然后减去,但它应该采用初始输入并不断从中减去

我的程序是薪水计算器。

在此处输入图片说明

您只需要将newSalaryAmount应用于当前的salaryAmount

private void Button2_Click(object sender, RoutedEventArgs e)
{
    try
    {
        subtractAmount = double.Parse(TextBox2.Text);
        newSalaryAmount = salaryAmount - subtractAmount;

        //Set the new current salary
        salaryAmount = newSalaryAmount
        label1.Content = newSalaryAmount.ToString();
    }
    catch (Exception)
    {
        MessageBox.Show("This was not a valid input.");
    }
} 

在您的情况下, salaryAmount将始终保持从TextBox1.Text给定的初始值,因此当您再次减少该值时,它将采用此后没有改变的值。

暂无
暂无

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

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