-3

How would I create a polynomial function using an array? Basically I want to display the polynomial (ex. x^2 + 3x + 5). Then, I want to show what the highest polynomial degree is. For example, x^2 + 3x + 5 = 2 (highest degree).

takendarkk
  • 3,347
  • 8
  • 25
  • 37

2 Answers2

1
// initial highest exponent
int exponent = 0;

// We're assuming [in] is a stream such as istream in C++.
if (char == ^)
{
     in >> char;

     if (char > initial)
     {
          initial = char)
     }
 }

We also have to check if the char after x is a +, -, or white space. We want to also check for that exponent.

Will
  • 24,082
  • 14
  • 97
  • 108
White Lotus
  • 353
  • 2
  • 6
  • 16
1

I might recommend doing it like this.

        string polynomial = "x^2 + 3x + 5";
        int index = 0,highestdegree = 0;
        foreach (char character in polynomial) {
            if(character == '^')
            {
                index++;
                try{
                    int test;
                    int.TryParse(polynomial[index],out test);
                    if(test >highestdegree)
                        highestdegree = test;
                    index--;
                }
                catch{
                    index--;
                }
            }
            index += 1;
        }
      if(highest degree == 0)
       { 
            highestdegree == 1;
       }
      return highest degree;

You would have to turn your polynomial to a string first though.

Mindstormer
  • 299
  • 3
  • 16