【问题标题】:C# custom control exponential E not workingC# 自定义控件指数 E 不起作用
【发布时间】:2016-03-30 23:58:52
【问题描述】:

我正在做一个新的整数框,我希望它只接受整数和指数 E。我知道做指数 E 你必须做 Math.Exp(x) 但我似乎找不到放置它的正确位置。有人可以帮帮我吗?

namespace IntegerBox
{
    public partial class IntBox : TextBox
    {
        private double intNum;

        public double IntNum
        {
            get { return intNum; }
            set { intNum = value; }
        }

        public IntBox()
        {   // set initial values to prperty Text, Event handlers properties TextChanged, Leave
            this.Text = "0";

            this.TextChanged += new EventHandler(IntBox_TextChanged);
            this.Leave += new EventHandler(IntBox_Leave);
            this.Math.Exp();
            InitializeComponent();
        }

        protected void IntBox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                IntNum = Convert.ToDouble(this.Text);

                Math.Exp(intNum);
            }
            catch (FormatException)
            {
                  MessageBox.Show("Other than Integer number entered",
                   "Your error was",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        protected void IntBox_Leave(object sender, EventArgs e)
        {
            intNum = Convert.ToDouble(this.Text);
            Math.Exp(intNum);
            //intNum = Math.Exp(this.Text);
        }

        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
        }

        private void IntBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                intNum = Convert.ToDouble(this.Text);
                Math.Exp(intNum);
                // intNum = Math.Exp(this.Text);
            }

        }
    }
}

【问题讨论】:

  • Math.Exp 返回新值。你对这个值什么都不做
  • 那么我应该怎么做才能让它接受指数 e?因为我到处找,什么都找不到
  • 检查 MSDN 以获取 Math.Exp() 的返回类型,将其分配给变量并显示在您的控件上。
  • 无论如何你想对计算结果做什么?在某处显示它?
  • 是的,然后我做了一个表格,只让用户输入整数和指数 e

标签: c# exponential


【解决方案1】:

首先,既然要获取整数值,就应该这样声明:

// use Int64 to allow larger numbers. Otherwise stick to the classic int type
private Int64 intNum;

public Int64 IntNum
{
    get { return intNum; }
    set { intNum = value; }
}

我假设您希望允许整数值接近科学记数法(即具有指数 E 的数字)给您的值,因为 E 数字是双精度值。

try
{
    IntNum = Convert.ToDouble(this.Text);
    Math.Exp(intNum);
}

可以变成

try
{
    IntNum = ConvertToInt64(Convert.ToDouble(this.Text));
}
catch (...)
{

}

out of range values 和invalid format 会得到不同的异常,因此单独处理 FormatException 是不够的。

整个解决方案的另一个方面是其复杂性。考虑使用Binding,因为它会自动处理数据传输(从属性到控制,反之亦然)。

【讨论】:

  • 双值也是可以接受的,这就是我加倍的原因(对不起,我没有充分解释自己是我的错),我遇到的问题是指数问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 2018-06-01
  • 1970-01-01
相关资源
最近更新 更多