如果找到(。),如何使条件成为假

时间:2017-02-13 18:01:15

标签: c# .net

我是c#的新手。我正在尝试用c#构建计算器。一切正常,小数点系统工作正常,但我的主要问题是我不希望小数重复多次。目前如果我把0.1 + 0.1我会得到0.2。但是我想要像计算器一样使用小数点。我确实将构造函数中的条件设置为isDecimal = false并在此之后创建新数字。所以它会认识到并且失败了。有人可以帮我解决我做错的事吗。谢谢。请尝试给出简单的解释,以便我能理解,而且我也是新的

using System;
   using System.Collections.Generic;
  using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
 using System.Threading.Tasks;
using System.Windows.Forms;

namespace Calc
{

public partial class Form1 : Form
{
    /// <summary>
    /// This is a constructor which will run atleast once. This will also create new number 
    /// </summary>
    public Form1()
    {

        InitializeComponent();
        memory = 0;
        txtResult.Text = "0";
        t = 0;
        h = 0;
        count = 0;

        //boolean Type
        isDecimal = false;
        creatingNewNumber = true;  // saying we we want to create the new number
    }
    private double leftSide;
    private bool creatingNewNumber;
    private double rightSide;
    private double memory;
    private string operators;
    private double t;
    private double h;
    private double count;
    private bool isDecimal;

    /// <summary>
    /// A function to add two numbers.
    /// </summary>
    /// <param name="x">Left Side of an addition</param>
    /// <param name="y">Right Side of an addition</param>
    /// <returns>Returns the answer to the addition.</returns>
    public double add(double x, double y)
    {
        //do sdome work
        leftSide = x;
        rightSide = y;

        double z = leftSide + rightSide;

        return z;
    }


    /// <summary>
    /// Function to add substract
    /// </summary>
    /// <param name="x">Left Side </param>
    /// <param name="y">Right Side</param>
    /// <returns>Returns the answer in substraction</returns>

    public double substract(double x, double y)
    {
        leftSide = x;
        rightSide = y;

        double s = leftSide - rightSide;

        return s;
    }

    /// <summary>
    /// Function to call the multiply
    /// </summary>
    /// <param name="x">Left side</param>
    /// <param name="y">Right Side</param>
    /// <returns>Returns the value in multiplication</returns>
    public double multiply(double x, double y)
    {

        leftSide = x;
        rightSide = y;

        double m = leftSide * rightSide;

        return m;
    }

    /// <summary>
    /// function to call the division and also stating that if the number on right is 0 throw an error.
    /// </summary>
    /// <param name="x">Left Side</param>
    /// <param name="y">Right Side</param>
    /// <returns>Return the value in division</returns>
    public double divide(double x, double y)
    {
        double d;
        leftSide = x;
        rightSide = y;

        if (rightSide == 0)
        {
            MessageBox.Show("Cannot divide by zero");
            return 0;
        }
        else
        {
            d = leftSide / rightSide;
        }
        return d;
    }

    /// <summary>
    /// The function does division. In addition what it does is store the memory value in y and 
    /// then at last it creates the conditional value wheather to create new value or to append
    /// the value when the operator is press which is (+-*/)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void divide_Click(object sender, EventArgs e)   // divide
    {
        bool StillOK = true;
        double y;
        if (!double.TryParse(txtResult.Text, out y))
        {
            MessageBox.Show("Right Side is not a valid number");
            StillOK = false;
        }
        if (StillOK)
        {
            memory = y;
            operators = "/";
            creatingNewNumber = true;
        }
    }


    /// <summary>
    /// The function does division. In addition what it does is store the memory value in y and 
    /// then at last it creates the conditional value wheather to create new value or to append
    /// the value when the operator is press which is (+-*/)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void multiply_Click(object sender, EventArgs e)  // multiply function
    {
        bool StillOK = true;
        double y;

        if (!double.TryParse(txtResult.Text, out y))
        {
            MessageBox.Show(txtResult.Text + " is not a valid number");
            StillOK = false;
        }
        if (StillOK)
        {
            memory = y;
            operators = "*";
            creatingNewNumber = true;
        }
    }

    /// <summary>
    /// The function does division. In addition what it does is store the memory value in y and 
    /// then at last it creates the conditional value wheather to create new value or to append
    /// the value when the operator is press which is (+-*/)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void add_Click(object sender, EventArgs e)  // add function
    {
        bool StillOK = true;
        double y;
        if (!double.TryParse(txtResult.Text, out y))
        {
            MessageBox.Show(txtResult.Text + " is not a valid number");
            StillOK = false;
        }
        if (StillOK)
        {
            memory = y;
            operators = "+";
            creatingNewNumber = true;

        }
    }
    /// <summary>
    /// The function does division. In addition what it does is store the memory value in y and 
    /// then at last it creates the conditional value wheather to create new value or to append
    /// the value when the operator is press which is (+-*/)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void substract_Click(object sender, EventArgs e) // substract function
    {
        bool StillOK = true;
        double y;

        if (!double.TryParse(txtResult.Text, out y))
        {
            MessageBox.Show(txtResult.Text + " is not a valid number");
            StillOK = false;
        }
        if (StillOK)
        {
            memory = y;
            operators = "-";
            creatingNewNumber = true;
        }
    }
    /// <summary>
    /// This function resets the Txt Result box to zero
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button5_Click(object sender, EventArgs e)  // clear function
    {

        memory = 0;
        txtResult.Text = "0";
        creatingNewNumber = true;
    }

    /// <summary>
    /// This Function will focus on decimal Point 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button19_Click(object sender, EventArgs e)  //decimal point                   ( . ) 
    {
        if (isDecimal)
        {
            txtResult.Text = ".";
            isDecimal = true;
            creatingNewNumber = true;

        }
        txtResult.Text += "."; // should add one more decimal point 
    }


    private void button14_Click(object sender, EventArgs e)
    {
        double equal;
        if (!double.TryParse(txtResult.Text, out equal))
        {
            MessageBox.Show(txtResult + "This is not an valid.");
        }
        else
        {
            switch (operators)
            {
                case "+":
                    memory = add(memory, equal);
                    break;
                case "-":
                    memory = substract(memory, equal);
                    break;
                case "/":
                    memory = divide(memory, equal);
                    break;
                case "*":
                    memory = multiply(memory, equal);
                    break;
                default:

                    break;
            }

            txtResult.Text = memory.ToString();  // convert text to string result 
            creatingNewNumber = true;
        }
    }

我做错了什么?任何建议都将受到欢迎。谢谢你的帮助

编辑:现在我可以点击0..1我试图阻止它,只想显示0.1(不再使用。应该允许使用。)

5 个答案:

答案 0 :(得分:1)

我不确定为什么你需要在你的十进制块中使用所有这些

private void button19_Click(object sender, EventArgs e)  
{
    if (isDecimal)
    {
        txtResult.Text = ".";
        isDecimal = true;
        creatingNewNumber = true;
    }
    txtResult.Text += "."; // should add one more decimal point 
}

应该是这样的

private void button19_Click(object sender, EventArgs e)  
{
    if (txtResult.Text == string.Empty || txtResult.Text.IndexOf('.') > -1)
        return;
    txtResult.Text += "."; 
}

注意:我看到这里的其他答案会告诉你一些关于文本验证,关键新闻事件等等 - 你不需要关于文本框。所有表格按键都应指向按钮点击。文本框应该是只读的,一旦你禁用任何直接的键盘到文本框输入,你只需要检查是否按下了按钮&#34;。&#34;,如果点已经存在绕过。

答案 1 :(得分:0)

进行此类文本验证的一种方法是使用正则表达式:

^[0-9]+(\.[0-9]+)?$

其中
^表示&#34;字符串的开头&#34;
[0-9]+表示&#34; 1个或更多数字&#34; ([...]表示字符类 - 即字符的选择)
$表示&#34;字符串结尾&#34;
\.表示一个文字句点(通常,.表示&#34;任何字符都是&#34; - 反斜杠表示它是一个替代意义而不是&#34;通常& #34;含义)
?表示&#34; 0或1次&#34; (即小数部分是可选的,但是如果他们拥有它只能出现一次)

这会导致无效输入的一些示例:

  • 0.1
  • 1
  • 1 ... 2
  • 1.2.3

答案 2 :(得分:0)

好的所以我找到了答案,零确实包含了。 更新代码

 if (creatingNewNumber == true)
        {
            if (txtResult.Text.IndexOf('.') == -1)
            {
                creatingNewNumber = false;
                txtResult.Text += ".";
            }
            else
            {
                txtResult.Text = "0.";
                creatingNewNumber = false;
            }

答案 3 :(得分:0)

我不知道您是显示数学运算还是仅显示最终结果,但如果您在文本框中显示完整操作(例如; 5 + 1.2 = 6.2),以下内容可帮助您进行一些验证关于文字的变化:

 private void textBox1_TextChanged(object sender, EventArgs e)
    {
        int lastOperatorIndex = ((TextBox)sender).Text.LastIndexOfAny(new char[] { '+', '-', '/', '*' });

        lastOperatorIndex = lastOperatorIndex < 0 ? 0: lastOperatorIndex + 1;


        // Check if the new added character is '.' and the if last number has already a decimal point then prevent the change.
        if (((TextBox)sender).Text.Last().Equals('.') &&  ((TextBox)sender).Text.Substring(lastOperatorIndex, textBox1.Text.Length - lastOperatorIndex - 1 ).Contains('.'))
        {
            textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
        }
    }

答案 4 :(得分:-1)

将TextChanged事件添加到您的输入中。在TextChanged事件中,添加

myInput = new Regex("[.]{2,}", RegexOptions.None).Replace(myInput, ".");

这将在用户输入时进行处理,如果他们复制粘贴,并且会在他们尝试处理的任何时候覆盖&#34;。&#34;。

为了使用户能够很好地处理,可以使用简单的插入符号控件:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    int currentCharIndex = textBox1.SelectionStart;
    Regex r = new Regex("[.]{2,}", RegexOptions.None);

    if (r.IsMatch(textBox1.Text))
    {
        textBox1.Text = r.Replace(textBox1.Text, ".");
        if(textBox1.SelectionStart > 0)
            textBox1.SelectionStart = currentCharIndex - 1;
    }
}

(警告,对于非常大的字符串输入,这可能效率很低,但对于你正在做的事情,它应该处理得很好)。

编辑:如果您点击按钮,它将删除焦点,固定使其只有在索引大于0时才会执行此操作(如果没有焦点或在开头时它为0)