【问题标题】:Displaying in a Method在方法中显示
【发布时间】:2025-11-23 15:45:01
【问题描述】:

编辑:我能够添加和显示多项式,但我如何摆脱最后的额外加号?这是当前显示的内容:

多项式方程

7x^5+3x^4+10x^3+2x^2+15x^1+5x^0+1x^5= 8x^5+3x^4+10x^3+2x^2+15x^1+5x^0+

回车键退出

最后的加号是我想去掉的^

这是我现在拥有的代码。如果您需要澄清,请告诉我!

static void Main(string[] args)
    {
        int[] intCoefficients = new int[6] { 5, 15, 2, 10, 3, 7 };
        Polynomial firstpolynomial = new Polynomial(5);
        Polynomial secondpolynomial = new Polynomial(5, intCoefficients);
        Polynomial polynomialthree = new Polynomial();
        polynomialthree = firstpolynomial + secondpolynomial;

        Console.WriteLine("Polynomial Equation");
        Console.WriteLine("");

        //call the method
        secondpolynomial.Display();
        firstpolynomial.Display();
        polynomialthree.Display();

        Console.WriteLine("");
        Console.WriteLine("");
        Console.WriteLine("Press Enter to Exit");
        Console.ReadLine();

    }
}
class Polynomial: IComparable 
{
    //fields
    int intDegree;
    int[] intCoefficient = new int[6];

    //uses IComparable
    int IComparable.CompareTo(Object o)
    {
        int returnVal = -1;
        Polynomial temp = (Polynomial)o;
        if (this.Degree > temp.Degree)
        {
            returnVal = 1;
        }
        else
        {
            if (this.Degree < temp.Degree)
            {
                returnVal = -1;
            }
            else
            {
                returnVal = 0;
            }
        }
        return returnVal;
    }

    //properties
    public int Degree
    {
        get
        {
            return intDegree;
        }
        set
        {
            intDegree = value;
        }
    }
    public int[] Coefficient
    {
        get
        {
            return intCoefficient;
        }
        set
        {
            for (int x = 0; x < value.Length; x++)
            {
                intCoefficient[x] = value[x];
            }
        }
    }

    //constructors
    public Polynomial() //this constructor creates the polynomial 0
    {
        for (int x = 0; x < intCoefficient.Length; x++)
        {
            intCoefficient[x] = 0;
            intDegree = 0;
        }
    }
    public Polynomial(int intDegree) //creates x^5 polynomial
    {
        this.intDegree = intDegree;
        for (int x = 0; x < intCoefficient.Length; x++)
        {
            intCoefficient[x] = 0;
        }
        intCoefficient[intDegree] = 1;
    }
    public Polynomial(int intDegree, int[] intArray) //creates other polynomial
    {
        this.intDegree = intDegree;
        for (int x = 0; x < intCoefficient.Length; x++)
        {
            intCoefficient[x] = 0;
        }
        for (int x = 0; x < intArray.Length; x++)
        {
            intCoefficient[x] = intArray[x];
        }
    }
    public override string ToString() //creates polynomial equation and returns to Main()
    {

        string strPolynomial = "";

        for (int x = intDegree; x >= 0; x--)
        {
            if (intCoefficient[x] > 0 && intCoefficient[x] != 1)
            {
                strPolynomial += intCoefficient[x].ToString() + "x^" + x.ToString() + "+";
            }
            else
            {
                if (intCoefficient[x] == 1)
                {
                    strPolynomial += intCoefficient[x].ToString() + "x^" + x.ToString() + "="; 
                }
            }
        }

        return strPolynomial;
    }
    //adds first two polynomials together and returns result to the third polynomial
    public static Polynomial operator +(Polynomial firstpolynomial, Polynomial secondpolynomial)
    {
        int intAddedDegree;
        int[] intAddedCoefficient = new int[6];

        if (firstpolynomial.Degree > secondpolynomial.Degree)
        {
            intAddedDegree = firstpolynomial.Degree;
        }
        else
        {
            intAddedDegree = secondpolynomial.Degree;
        }
        for (int x = 0; x < intAddedCoefficient.Length; x++)
        {
            intAddedCoefficient[x] = firstpolynomial.Coefficient[x] + secondpolynomial.Coefficient[x];
        }

        Polynomial result = new Polynomial(intAddedDegree, intAddedCoefficient);

        return result;
    }
    //display method
    public void Display() //couldn't figure out how to make the plus go away
    {
        for (int x = intDegree; x >= 0; x--)
        {
            if (intCoefficient[x] > 0 && intCoefficient[x] != 1)
            {
                Console.Write(intCoefficient[x].ToString() + "x^" + x.ToString() + "+");
            }
            else
            {
                if (intCoefficient[x] == 1)
                {
                    Console.WriteLine(intCoefficient[x].ToString() + "x^" + x.ToString() + "=");
                }
            }
        }
    }

【问题讨论】:

  • 你试过polynomialthree.Display()吗?
  • 您需要在 Polynomial 类中覆盖 ToString 以使其按照您现在的方式工作,或者摆脱 Console.WriteLines 并调用 firstpolynomial.Display() (等)而是。
  • 好的,感谢您的帮助!我只是想通了,但现在因为我决定在显示方法中显示它弄乱了顺序,所以它不是从最高到最低的指数显示。相反,它的显示从最低到最高。我知道我必须使用 Array.Sort() 来做到这一点,但我不知道如何对三个多项式进行排序
  • 对于所有更新以及如有任何混淆,我深表歉意。在过去的几分钟里,我一直在研究这个问题,并且能够使它工作,但有一个例外。当它显示多项式时,它会在等式末尾显示一个加号。我该如何摆脱这个?多项式 7x^5+3x^4+10x^3+2x^2+15x^1+5x^0+1x^5= 8x^5+3x^4+10x^3+2x^2+15x^1+ 5x^0+ 按 Enter 退出
  • 通过删除添加加号的部分代码。

标签: c# arrays class methods


【解决方案1】:

不是一个小问题,你有很多代码质量问题。尝试理解这段代码,恕我直言,它更加灵活、精简和健壮。

所有有趣的逻辑都在ToString() 中,它创建了一个多项式字符串。 diplay 函数只是将ToString() 的输出写入控制台窗口。

static class Program
{
    internal static void Main(string[] args)
    {
        int[] intCoefficients = new int[] { 5, 15, 2, 10, 3, 7 };
        Polynomial firstpolynomial = new Polynomial(5);
        Polynomial secondpolynomial = new Polynomial( intCoefficients );
        Polynomial polynomialthree;
        polynomialthree=firstpolynomial+secondpolynomial;

        Console.WriteLine("Polynomial Equation");
        Console.WriteLine();

        //call the method
        secondpolynomial.Display();
        firstpolynomial.Display();
        polynomialthree.Display();

        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("Press Enter to Exit");
        Console.ReadLine();
    }
}

public class Polynomial : IComparable, IComparable<Polynomial>
{
    readonly int[] intCoefficient;
    //constructors
    public Polynomial() //this constructor creates the polynomial 0
        : this(0) { }
    public Polynomial(int intDegree) //creates x^5 polynomial
    {
        this.intCoefficient=new int[intDegree+1];
        this.intCoefficient[intDegree]=1;
    }
    public Polynomial(params int[] intArray) //creates other polynomial
    {
        this.intCoefficient=intArray;
    }

    //properties
    public int Degree
    {
        get
        {
            return intCoefficient.Length-1;
        }
    }
    public int[] Coefficient
    {
        get
        {
            return intCoefficient;
        }
    }

    /// <summary>
    /// Converts the polynomial to a string representation
    /// </summary>
    /// <returns>A string object</returns>
    public override string ToString() 
    {
        StringBuilder result = new StringBuilder();
        for (int i=0; i<=Degree; i++)
        {
            int coef = intCoefficient[i];
            int sign = Math.Sign(coef);
            coef=Math.Abs(coef);
            if (coef>0)
            {
                if (sign<0)
                {
                    // always add a leading negative when needed
                    result.Append("-");
                }
                else if (result.Length>0)
                {
                    // only add a leading plus if not first term
                    result.Append("+");
                }
                // append Cx^i terms
                if (coef>1&&i>1)
                {
                    result.AppendFormat("{0}x^{1}", coef, i);
                }
                else if (coef>1&&i==1)
                {
                    result.AppendFormat("{0}x", coef);
                }
                else if (coef>1&&i==0)
                {
                    result.AppendFormat("{0}", coef);
                }
                else if (coef==1&&i==1)
                {
                    result.Append("x");
                }
                else if (i==0)
                {
                    result.Append(coef.ToString());
                }
                else
                {
                    result.AppendFormat("x^{0}", i);
                }
            } // ignore term of coef==0
        }            
        return result.ToString();
    }

    /// <summary>
    /// Adds the coefficients of two polynomials
    /// </summary>
    /// <param name="firstpolynomial">A polynomial</param>
    /// <param name="secondpolynomial">Another polynomial</param>
    /// <returns>The resulting polynomial</returns>
    public static Polynomial operator +(Polynomial firstpolynomial, Polynomial secondpolynomial)
    {
        // Always make sure the first polynomial has equal or more terms
        if (secondpolynomial.Degree>firstpolynomial.Degree)
        {
            // Reverse the operation
            return secondpolynomial+firstpolynomial;
        }
        // Result must have same degree as first poly
        int result_degree = firstpolynomial.Degree;
        int[] result_coef = new int[result_degree+1];
        for (int i = 0; i<secondpolynomial.intCoefficient.Length; i++)
        {
            // Add coefficients from two polynomials
            result_coef[i]=firstpolynomial.intCoefficient[i]+secondpolynomial.intCoefficient[i];
        }
        for (int i = secondpolynomial.intCoefficient.Length; i<result_coef.Length; i++)
        {
            // Assign remaining coefficients from fist polynomial
            result_coef[i]=firstpolynomial.intCoefficient[i];
        }
        return new Polynomial(result_coef);
    }
    //display method
    public void Display() 
    {
        Console.WriteLine(ToString());
    }

    public int CompareTo(Polynomial other)
    {
        // Just compare the order of the polynmomials
        return Degree.CompareTo(other.Degree);
    }
    int IComparable.CompareTo(Object o)
    {
        if (o is Polynomial)
        {
            return CompareTo(o as Polynomial);
        }
        return 0;
    }
}

输出是

Polynomial Equation

5+15x+2x^2+10x^3+3x^4+7x^5
x^5
5+15x+2x^2+10x^3+3x^4+8x^5


Press Enter to Exit

【讨论】:

  • 虽然我确实看到了精简和优化代码的目的,但除了额外的优点之外,这段代码确实有效。此外,我考虑过更改某人引用的 intCoefficiants.Length - 1 的 7,这应该使代码正常工作,除非多项式类中的数组也必须更改。我的主要目标是让代码正常工作,然后对其进行优化。
  • a) 您的代码在 ToString()Display() 之间有重复代码。 b)您的代码限制了多项式顺序。 c) 您的代码使 Polynomial 是可变类型,这通常会导致副作用。 d) 您的代码在构造函数之外初始化一个实例。 e) 当指数为 1 或系数为 0 或 1 时,您的代码不会简化输出。最后,您的代码使用匈牙利表示法,C# 不鼓励这种表示法(我保留它以尽量减少代码的更改)。
最近更新 更多