简体   繁体   中英

c# Horner Exercise wrong answer

I have a problem with an exercise. The program has to count using the Horner scheme. I have tried my best but I always get the wrong answer, I'm afraid i have done a small mistake that can be fix easily. I dont know what to do and I hope someone will help me solve this problem.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FeelsBadMan
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    int i, a, x, h, n;
                    int[] array = new int[100];
                    Console.Write("Degree of a polynomial: ");
                    a = Convert.ToInt32(Console.ReadLine());
                    Console.Write("Constant term : ");
                    n = Convert.ToInt32(Console.ReadLine());


                    for (i = 1; i <= a; i++)
                    {
                        Console.Write("Input number x^{0}: ", i);
                        array[i] = Convert.ToInt32(Console.ReadLine());
                    }
                    Console.Write("Input x value: ");
                    x = Convert.ToInt32(Console.ReadLine());
                    {
                        h = array[0];
                        for (i = 1; i < a; i++)
                        {
                            h = (h * x) + array[i] + n;
                        }
                        Console.Write("Result: {0}\n", h);
                        Console.ReadKey();
                        break;
                    }
                }
                catch (OverflowException)
                {
                    Console.WriteLine("Number out of scale! Try again.\n");
                }
                catch (FormatException)
                {
                    Console.WriteLine("Incorrect format! Try again.\n");
                }
            }
        }
    }
}

For example:

Degree of a polynomial:3
Constant term: 5
Input number x^1: 1
Input number x^2: 0
Input number x^3: 1
Input x value: 3
Result: 23

However the correct answer is 35.

This outputs the correct result:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FeelsBadMan
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    Console.Write("Degree of a polynomial: ");
                    Int32 a = Convert.ToInt32(Console.ReadLine());

                    Console.Write("Constant term : ");
                    Int32 n = Convert.ToInt32(Console.ReadLine());

                    List<Int32> polys = new List<Int32>(a + 1);

                    for (Int32 i = 1; i <= a; ++i)
                    {
                        Console.Write("Input number x^{0}: ", i);
                        polys.Add(Convert.ToInt32(Console.ReadLine()));
                    }

                    polys.Insert(0,n);

                    Console.Write("Input x value: ");
                    Int32 x = Convert.ToInt32(Console.ReadLine());

                    Int32 result = array[a];

                    for (Int32 i = a - 1; i >= 0; --i)
                        result = (result * x) + polys[i];

                    Console.Write("Result: {0}\n", result);
                    Console.ReadKey();
                }
                catch (OverflowException)
                {
                    Console.WriteLine("Number out of scale! Try again.\n");
                }
                catch (FormatException)
                {
                    Console.WriteLine("Incorrect format! Try again.\n");
                }
            }
        }
    }
}

You included your constant term to the result in every iteration, that was the main problem! Also, as @Peter Duniho pointed out, Horner's method requires starting with the highest-order coefficient and going to the lowest, so I inverted the iteration order.

Last but not least, you based your system on a fixed-length integers array, which is not really a good practice in this case. I used instead a List<Int32> instead, which is much better, initialized with a fixed capacity equal to a + 1 in order to take care of the constant term too, which is gonna be appended to index 0 once all the polynomials have been defined.

On a side note, if this code must be released, don't forget to add sanity checks to see if user input is correct.

You have three separate problems in your loop:

  1. Your initial value is set to array[0] , which is an uninitialized element of the array and so has the value 0 . This should instead be set to the highest-order coefficient of the polynomial, ie array[a] .
  2. You are, for some inexplicable reason, adding the constant term, ie the lowest-order coefficient, on every iteration of the loop.
  3. Last, but certainly not least, you are computing the values in the wrong order, starting with the lowest-order coefficient and going to the highest. Horner's method requires starting with the highest-order coefficient and going to the lowest.

Implementing the algorithm straight from the Wikipedia article , your loop should instead look like this:

array[0] = n;
int h = array[a];

for (int i = a - 1; i >= 0; i--)
{
    h = array[i] + h * x;
}

That will produce the expected result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM