Vb.net 从文本框计算表达式(如45/12)

Vb.net 从文本框计算表达式(如45/12),vb.net,Vb.net,我需要能够在文本框中键入45/12或3.75的值,这是十进制-英寸转换。显然,十进制值是有效的。代码采用不同的文本框值(a),该值(b)从a中减去b,并将结果乘以收缩因子,以填充到另一个文本框中。有些人知道十进制转换,有些人不知道,于是求助于45/12方法。值(a)严格按照十进制转换输入,8'-1“将为8.0833。在此方面的任何帮助都将不胜感激。值(b)但是,在代码中用于进一步的计算,如果需要,我可以发布。这是代码的一部分,b的值会持续到>4的表达式。这也是我第一次使用VB设计,因此它可能不是

我需要能够在文本框中键入45/12或3.75的值,这是十进制-英寸转换。显然,十进制值是有效的。代码采用不同的文本框值(a),该值(b)从a中减去b,并将结果乘以收缩因子,以填充到另一个文本框中。有些人知道十进制转换,有些人不知道,于是求助于45/12方法。值(a)严格按照十进制转换输入,8'-1“将为8.0833。在此方面的任何帮助都将不胜感激。值(b)但是,在代码中用于进一步的计算,如果需要,我可以发布。这是代码的一部分,b的值会持续到>4的表达式。这也是我第一次使用VB设计,因此它可能不是最有效的代码。谢谢

Option Explicit On
Public Class Form1



Dim a, b, c, d, r, w, h, x, y, z As Single
Dim s, t, u, v, f, g, j, k, l, m, n, o As Single

Private Sub radiobutton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
    If (RadioButton1.Checked) = False Then
        Button1.PerformClick()
    End If
End Sub

Private Sub radiobutton3_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton3.CheckedChanged
    If (RadioButton3.Checked) = False Then
        Button1.PerformClick()
    End If
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    If Timer1.Interval = 1000 Then
        Label9.Text = DateTime.Now
    End If
End Sub


' Calculate Button Does This
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click



    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Error Boxes

    If TextBox1.Text = "" Then
        MsgBox("Please Input 'Wall Height' And/Or 'Depth'")
        With TextBox1
            .Focus()
            .SelectAll()
        End With
        Exit Sub
    End If

    If TextBox2.Text = "" Then
        MsgBox("Please Input 'Wall Height' And/Or 'Depth'")
        With TextBox2
            .Focus()
            .SelectAll()
        End With
        Exit Sub
    End If

    If (RadioButton1.Checked Or RadioButton3.Checked) = False Then
        MsgBox("Please Select 'N/A' or 'Yes")
    End If

    If TextBox1.Text < TextBox2.Text Then
        MsgBox("Re-check Depth and Wall Height")
        With TextBox1
            .Focus()
            .SelectAll()
        End With
        Exit Sub
    End If


    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Values For Depth And Wall Height

    a = Val(TextBox1.Text) 'Depth
    b = Val(TextBox2.Text) 'Actual Wall Height



    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Hopper Drop Shrink Calculation

    If (RadioButton3.Checked) AndAlso ((a - b) <= 1) Then
        r = Math.Round(((a - b) - 0.0833), 4)
    ElseIf (RadioButton1.Checked) Then
        r = Math.Round(((a - b) * 0.944), 4) ' Depth minus wall height .944 shrink factor
    ElseIf (RadioButton3.Checked) Then
        r = Math.Round(((a - b) * 0.89), 4) ' Depth minus wall height .89 shrink factor
    End If

    If r <= 0.01 Then
        TextBox3.Text = "N/A"
    Else : TextBox3.Text = r
    End If
    ' Value For Hopper Drop after shrink





    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Depth Minus Wall Height Ranges For Finish Wall Height

    w = (b >= 0.0833 And b <= 3.25) ' Wall height between 12" and 39"
    If w Then
        h = Math.Round(((b - 0.0833) * 12), 2) ' Subtract 1" from wall height
    End If

    If w Then
        t = 0
    End If

    If w Then
        d = 0
    End If


    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    z = (b >= 3.26 And b <= 3.3332) ' Wall height between 39 1/4" and 39 3/4"
    If z Then
        h = 38 ' Wall height will be 38"
    End If

    If z Then
        t = 0
    End If

    If z Then
        d = 0
    End If

TextBox4.Text = Int(h) & " " & DecToFraction(h - Int(h)) & "''" 'Finish Wall Height
    TextBox6.Text = Int(t) & " " & DecToFraction(t - Int(t)) & "''" ' Strip Size
    If CheckBox2.Checked Then
        TextBox5.Text = "N/A"
    ElseIf CheckBox2.Checked = False Then
        TextBox5.Text = Int(t) & " " & DecToFraction(t - Int(t)) & "''" ' Wrap Size
    End If

    TextBox7.Text = Int(d) & " " & DecToFraction(d - Int(d)) & "''" ' Cut wall to (production wall height)
选项显式打开
公开课表格1
尺寸a、b、c、d、r、w、h、x、y、z为单个
单件尺寸s、t、u、v、f、g、j、k、l、m、n、o
私有子radiobutton1\u CheckedChanged(发送方作为对象,e作为事件参数)处理radiobutton1.CheckedChanged
如果(RadioButton1.选中)=False,则
按钮1.PerformClick()
如果结束
端接头
私有子radiobutton3\u CheckedChanged(发送方作为对象,e作为事件参数)处理radiobutton3.CheckedChanged
如果(RadioButton3.选中)=False,则
按钮1.PerformClick()
如果结束
端接头
私有子Timer1\u Tick(发送方作为对象,e作为事件参数)处理Timer1.Tick
如果Timer1.Interval=1000,则
Label9.Text=DateTime.Now
如果结束
端接头
'计算按钮执行此操作
私有子按钮1\u单击(发送者作为对象,e作为事件参数)处理按钮1。单击
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'错误框
如果TextBox1.Text=”“,则
MsgBox(“请输入“墙高”和/或“深度”)
使用TextBox1
.Focus()
.SelectAll()
以
出口接头
如果结束
如果TextBox2.Text=”“,则
MsgBox(“请输入“墙高”和/或“深度”)
使用TextBox2
.Focus()
.SelectAll()
以
出口接头
如果结束
如果(RadioButton1.Checked或RadioButton3.Checked)=False,则
MsgBox(“请选择“不适用”或“是”)
如果结束
如果TextBox1.TextIf(收音机按钮3.选中)和ALSO((a-b)=3.26和b您可以使用类似于将文本框输入视为数学表达式的库。这将完美地处理
45/12
3.75
,因为当通过表达式引擎执行时,两者都将计算为单个数字。

或者您可以使用如下结构:

class Program
{
    static void Main(string[] args)
    {
        Fraction X=Fraction.Parse("45/12");
        Console.WriteLine("X = {0} = {1} = {2}", X, X.GetReduced(),X.Value);
        // X = 45/12 = 15/4 = 3.75
        bool ok=X.Equals(3.75);
        // true
    }
}

/// <summary>
/// A Class to represent fraction from decimals using GCD and LCM.
/// </summary>
/// <remarks>Code taken from http://www.vcskicks.com/code-snippet/fraction.php</remarks>
[TypeConverter(typeof(ExpandableObjectConverter))]
public struct Fraction : IEquatable<Fraction>, IEquatable<double>, ICloneable
{
    public static string DefaultFormat="G";
    public readonly long numerator;
    public readonly long denominator;
    public static Fraction Zero=new Fraction(0, 1);

    public Fraction(long numerator, long denominator)
    {
        this.numerator=numerator;
        this.denominator=denominator;

        //If denominator negative...
        if(this.denominator<0)
        {
            //...move the negative up to the numerator
            this.numerator=-this.numerator;
            this.denominator=-this.denominator;
        }
    }

    public Fraction(Fraction fraction)
    {
        this.numerator=fraction.numerator;
        this.denominator=fraction.denominator;
    }

    public static Fraction Parse(string value)
    {
        long num=1;
        long den=1;
        string[] parts=value.Split('/');
        bool is_den=false;
        for(int i=0; i<parts.Length; i++)
        {
            if(is_den)
            {
                den*=long.Parse(parts[i]);
            }
            else
            {
                num*=long.Parse(parts[i]);
            }
            is_den=!is_den;
        }
        return new Fraction(num, den);
    }
    public static implicit operator Fraction(double value)
    {
        return Fraction.FromValue(value);
    }
    public static implicit operator double(Fraction rhs)
    {
        return rhs.Value;
    }

    public long Numerator { get { return numerator; } }
    public long Denominator { get { return denominator; } }
    public double Value { get { return (double)numerator/denominator; } }

    public static Fraction operator+(Fraction lhs, Fraction rhs) { return lhs.Add(rhs); }
    public static Fraction operator-(Fraction rhs) { return rhs.Negate(); }
    public static Fraction operator-(Fraction lhs, Fraction rhs) { return lhs.Subtract(rhs); }
    public static Fraction operator*(double lhs, Fraction rhs) { return rhs.Scale(lhs); }
    public static Fraction operator*(Fraction lhs, double rhs) { return lhs.Scale(rhs); }
    public static Fraction operator/(Fraction lhs, double rhs) { return lhs.Scale(1/rhs); }
    public static Fraction operator/(double lhs, Fraction rhs) { return rhs.Reciprocal(lhs); }
    public static Fraction operator*(Fraction lhs, Fraction rhs) { return lhs.Multiply(rhs); }
    public static Fraction operator/(Fraction lhs, Fraction rhs) { return lhs.Divide(rhs); }

    /// <summary>
    /// Get the greatest common divisor
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <returns></returns>
    private static long getGCD(long a, long b)
    {
        //Drop negative signs
        a=Math.Abs(a);
        b=Math.Abs(b);

        //Return the greatest common denominator between two integers
        while(a!=0&&b!=0)
        {
            if(a>b)
                a%=b;
            else
                b%=a;
        }

        if(a==0)
            return b;
        else
            return a;
    }
    /// <summary>
    /// Get the least common measure
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <returns></returns>
    private static long getLCM(long a, long b)
    {
        //Return the Least Common Denominator between two integers
        return (a*b)/getGCD(a, b);
    }

    public Fraction ToDenominator(long targetDenominator)
    {
        //Multiply the fraction by a factor to make the denominator
        //match the target denominator
        //Fraction modifiedFraction=this;
        long n=this.numerator;
        long d=this.denominator;

        //Cannot reduce to smaller denominators
        if(targetDenominator<this.denominator)
            return this;

        //The target denominator must be a factor of the current denominator
        if(targetDenominator%this.denominator!=0)
            return this;

        if(d!=targetDenominator)
        {
            long factor=targetDenominator/d;
            n*=factor;
            d=targetDenominator;
            //modifiedFraction.denominator=targetDenominator;
            //modifiedFraction.numerator*=factor;
        }

        return new Fraction(n, d);
    }

    public Fraction GetReduced()
    {
        //Reduce the fraction to lowest terms
        //Fraction modifiedFraction=this;
        long n=this.numerator;
        long d=this.denominator;

        //While the numerator and denominator share a greatest common denominator,
        //keep dividing both by it
        long gcd=0;
        while(Math.Abs(gcd=getGCD(n, d))!=1)
        {
            n/=gcd;
            d/=gcd;
        }

        //Make sure only a single negative sign is on the numerator
        n=n*Math.Sign(d);
        d=Math.Abs(d);

        return new Fraction(n, d);
    }
    /// <summary>
    /// Uses a continious fraction scheme to iteratively aproximate a number with a fraction. 
    /// The accuracy is taken from <see cref="GRE.Mathematics.Dbl.Calculator.ZeroTolerance"/>
    /// </summary>
    /// <remarks>See <see cref="FromValue(double,double)"/> to understand how it works</remarks>
    /// <param name="number">The number to approximate</param>
    /// <returns></returns>
    public static Fraction FromValue(double number)
    {
        return FromValue(number, 15);
    }
    /// <summary>
    /// Uses a continious fraction scheme to iteratively aproximate a number with a fraction
    /// </summary>
    /// <remarks>See <see cref="FromValue(double,double)"/> to understand how it works</remarks>
    /// <param name="number">The number to approximate</param>
    /// <param name="digits">The number if digits to use in the aproximation</param>
    /// <returns></returns>
    public static Fraction FromValue(double number, int digits)
    {
        double accuracy=Math.Pow(10.0, -digits);
        return FromValue(number, accuracy);
    }
    /// <summary>
    /// Uses a continious fraction scheme to iteratively aproximate a number with a fraction
    /// </summary>
    /// <remarks>
    /// See documentation for <see cref="FromContiniousFractionCoefficients(long[])"/> to understand how this works.
    /// </remarks>
    /// <param name="number">The number to aproximate</param>
    /// <param name="accuracy">The accuracy to use |fraction-value|<![CDATA[<]]>accuracy </param>
    /// <returns></returns>
    public static Fraction FromValue(double number, double accuracy)
    {
        int sign=Math.Sign(number);
        number=Math.Abs(number);
        int passes=0;
        List<long> coef=new List<long>();
        Fraction x;
        double r=number;  // remainder (example 8.22)
        do
        {
            long c=(int)r;    // integer of remainder (r=8.22 -> c=8)
            r=1/(r-c);    // new remainder from r -> 1/(0.22)=4.54
            coef.Add(c);        // adds c to the list
            x=FromContiniousFractionCoefficients(coef.ToArray());  // reconstruct the fraction from all the n's
            passes++;           // increment counter and repeat
        } while(!x.Equals(number, accuracy)&&passes<10);
        if(sign<0)
        {
            x=x.Negate();
        }
        return x;
    }
    /// <summary>
    /// Use recursion to take the integer coefficients of a continious fraction and simplify it to a regular fraction
    /// </summary>
    /// <example>The parameters in array <c>c</c> define the following value:<![CDATA[
    ///                  1
    ///  c[0] + -------------------- -> recursion on e[i] = c[i] + 1/e[i+1] , e[i]=r[i]/r[i+1]
    ///                    1
    ///       c[1] + ---------------         seed is 1/e[N]=0 (r[N]=1, r[N+1]=0)
    ///                       1              final result is x = r[0]/r[1]
    ///             c[2] + ---------      
    ///                     c[3]+...
    /// ]]></example>
    /// <remarks>Here are some references
    /// * http://www.friesian.com/golden.htm
    /// * http://archives.math.utk.edu/articles/atuyl/confrac/intro.html
    /// * http://www.trans4mind.com/personal_development/mathematics/numberTheory/continuedFractions.htm
    /// </remarks>
    /// <param name="coef">The integer coefficients for the fraction (see example)</param>
    /// <returns>A Fraction object</returns>
    public static Fraction FromContiniousFractionCoefficients(params long[] coef)
    {
        int N=coef.Length;
        if(N>0)
        {
            long[] r=new long[N+2];
            r[N+1]=0;
            r[N+0]=1;
            for(int i=N-1; i>=0; i--)
            {
                r[i]=coef[i]*r[i+1]+r[i+2];
            }
            return new Fraction(r[0], r[1]);
        }
        else
        {
            return Fraction.Zero;
        }
    }

    public Fraction Flip()
    {
        //Flip the numerator and the denominator
        return new Fraction(this.denominator, this.numerator);
    }

    public override bool Equals(object obj)
    {
        if(obj is Fraction)
        {
            return Equals((Fraction)obj);
        }
        return false;
    }
    public bool Equals(Fraction other, double tolerance)
    {
        return Math.Abs(Value-other.Value)<=tolerance;
    }
    public bool Equals(Fraction other)
    {
        var A=GetReduced();
        var B=other.GetReduced();
        return A.numerator==B.numerator&&A.denominator==B.denominator;
    }
    public override int GetHashCode()
    {
        unchecked
        {
            return 17*23*Value.GetHashCode();
        }
    }

    public Fraction Clone() { return new Fraction(this); }

    object ICloneable.Clone()
    {
        return Clone();
    }


    public Fraction Scale(double factor)
    {
        Fraction other=new Fraction(factor);
        return Multiply(other);
    }

    public Fraction Divide(double factor)
    {
        Fraction other=new Fraction(factor);
        return Divide(other);
    }

    public Fraction Reciprocal(double numerator)
    {
        Fraction other=new Fraction(numerator);
        return other.Divide(this);
    }

    public Fraction Multiply(Fraction other)
    {
        return new Fraction(numerator*other.numerator, denominator*other.denominator).GetReduced();
    }

    public Fraction Divide(Fraction other)
    {
        return new Fraction(numerator*other.denominator, denominator*other.numerator).GetReduced();
    }

    public Fraction Add(Fraction other)
    {
        return new Fraction(other.denominator*numerator+other.numerator*denominator, denominator*other.denominator).GetReduced();
    }

    public Fraction Subtract(Fraction other)
    {
        return new Fraction(other.denominator*numerator-other.numerator*denominator, denominator*other.denominator).GetReduced();
    }

    public Fraction Negate()
    {
        return new Fraction(-numerator, denominator);
    }



    public override string ToString()
    {
        return ToString(DefaultFormat);
    }

    public string ToString(string format)
    {
        return ToString(format, null);
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
        if(numerator==0)
        {
            string fmt="{0:#}".Replace("#", format);
            return string.Format(formatProvider, fmt, numerator);
        }
        else
        {
            string fmt="{0:#}/{1:#}".Replace("#", format);
            return string.Format(formatProvider, fmt, numerator, denominator);
        }
    }

    public bool Equals(double other)
    {
        return Value.Equals(other);
    }
    public bool Equals(double other, double tolerance)
    {
        return Math.Abs(Value-other)<=tolerance;
    }


}
类程序
{
静态void Main(字符串[]参数)
{
分数X=分数解析(“45/12”);
WriteLine(“X={0}={1}={2}”,X,X.GetReduced(),X.Value);
//X=45/12=15/4=3.75
布尔ok=X等于(3.75);
//真的
}
}
/// 
///使用GCD和LCM从小数中表示分数的类。
/// 
///代码取自http://www.vcskicks.com/code-snippet/fraction.php
[TypeConverter(typeof(ExpandableObjectConverter))]
公共结构分数:IEquatable、IEquatable、ICloneable
{
公共静态字符串DefaultFormat=“G”;
公共只读长分子;
公共只读长分母;
公共静态分数0=新分数(0,1);
公共分数(长分子、长分母)
{
这个。分子=分子;
这个。分母=分母;
//如果分母为负。。。
如果(这个分母)
公共静态分数FromValue(双倍数字,双精度)
{
整数符号=数学符号(数字);
数字=数学Abs(数字);
int passes=0;
List coef=新列表();
分数x;
double r=number;//余数(示例8.22)
做
{
长c=(int)r;//余数的整数(r=8.22->c=8)
r=1/(r-c);//r的新余数->1/(0.22)=4.54
添加(c);//将c添加到列表中
x=fromContiniusFractionCourters(coef.ToArray());//从所有n中重构分数
传递+++;//递增计数器并重复
}而(!x.Equals(数字、准确度)&&passes
///这里有一些参考资料
/// * http://www.friesian.com/golden.htm
/// * http://archives.math.utk.edu/articles/atuyl/confrac/intro.html
/// * http://www.trans4mind.com/personal_development/mathematics/numberTheory/continuedFractions.htm
/// 
///分数的整数系数(参见示例)
///分数物体
连续分形系数的公共静态分数(参数长[]系数)
{
int N=系数长度;
如果(N>0)
{
long[]r=新长[N+2];
r[N+1]=0;
r[N+0]=1;
对于(int i=N-1;i>=0;i--)
{
r[i]=coef[i]*r[i+1]+r[i+2];
}
返回新分数(r[0],r[1]);
}
其他的
{
返回分数。零;
}
}
公共分数翻转()
{
//翻转分子和分母
返回新分数(this.分母,this.分子);
}
公共覆盖布尔等于(对象对象对象)
{
if(obj是分数)
{
收益等于(分数)obj);
}
返回false;
}
公共学校