-4

As a user I have to input the size of an array and then fill it. For example if I input n=2,then first element =3,second =2 I need to calculate (X-3)(X-2). For this example output has to be 1,-5,6 ( cause (X-3)(X-2) = x^2 - 5*x + 6). I have no idea how to actually extract those coefficients.Do I have to work as if it was a string line? And how do I actually get to this expression "x^2 - 5*x + 6"? This is a piece of code that I have, but it just filling of the array

Console.WriteLine(  "Enter size of an array" );
            int size;
            Int32.TryParse(Console.ReadLine(), out size);


            var firstVector = new string[size];
            Console.WriteLine("Input first vector:");
            for (var i = 0; i <size; i++)
            {
                firstVector[i] = Console.ReadLine();
            }
            int[] firstVecInt = Array.ConvertAll(firstVector, int.Parse);
            Console.WriteLine("======================");

            foreach (var item in firstVecInt)
            {
                Console.Write(item.ToString() + " ");
            }
            Console.WriteLine(" first vector");

            for( var i =0; i< size;i++)
            {
                Console.Write("(x-" + firstVecInt[i] +")*");
            }
            Console.WriteLine("polynomial");

1 Answers1

1

It is a bit vague, but I might be able to give you some hints:

Input

You should be parsing those values as you get them. Do not keep them as strings. But you also have to deal with users entering soemthing invalid, wich happens often.

For consoles I like to use the do...while loop. Do (ask the user for input) while (he has not entered anything valid). Combine it with TryParse() and possibly a temporary bool variable and you can do it with very little code.

Math

In order to get the power of something, you need to use the Math.Pow method. Unfortunately it only deals with float/doubles. So you have to potentially consider Float Inprecision. There is no variant that takes Integers, unless you make the loop yourself or go for BigInteger. (How do you do *integer* exponentiation in C#?).

For the other math, be warned that the order of Operators might not be the same in C# as it is in math. Do not hesistate to limit it to one math operation per line by using a lot of temporary variables.

Christopher
  • 9,634
  • 2
  • 17
  • 31