我正在学习创建计算器程序。但是我对如何使数字为正数或负数感到沮丧。就像我们在普通计算器中看到的一样。
我不太确定如何通过使用文本框上的按钮使正数变为负数或使负号再次变为正数。

如果按一个按钮,数字将直接转到文本框。

私人void No1_Click(对象发送者,EventArgs e)

    {
        NumBox1.Text = NumBox1.Text + "1";
    }


如何使NumBox1.text中的数字为负号或正号?
请帮忙!!!!

我正在使用C#语言

最佳答案

如果我了解您对发布的两个答案的后续评论,则您不确定当时在框中输入的数值,并且需要知道如何在不进行分析的情况下取反该值,再乘以负数,ToString值并将其放回框中。

如果是这样,(并且您不想遵循上述过程,因为您可能会丢失尾随或前导零,或者只是不想更改用户的输入)

private void NegateButton_Click(object sender, EventArgs e)
{
    if(NumBox1.Text.StartsWith("-"))
    {
        //It's negative now, so strip the `-` sign to make it positive
        NumBox1.Text = NumBox1.Text.Substring(1);
    }
    else if(!string.IsNullOrEmpty(NumBox1.Text) && decimal.Parse(NumBox1.Text) != 0)
    {
        //It's positive now, so prefix the value with the `-` sign to make it negative
        NumBox1.Text = "-" + NumBox1.Text;
    }
}

07-28 07:37