简体   繁体   中英

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

I have the following code:

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);
    }
}

The problem is that it resets the number every time to the initial input and then subtracts but it should take an initial input and keep subtracting from it

My program is a salary calculator.

在此处输入图片说明

You simply need to apply the newSalaryAmount to your current 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.");
    }
} 

In your case salaryAmount would always stay the initial value given from TextBox1.Text so when you would go to reduce the value again it would take that value that has no changed since.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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