简体   繁体   English

C#Horner Exercise错误答案

[英]c# Horner Exercise wrong answer

I have a problem with an exercise. 我做运动有问题。 The program has to count using the Horner scheme. 该程序必须使用Horner方案进行计数。 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. 但是正确的答案是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. 另外,正如@Peter Duniho指出的那样,Horner的方法要求从最高阶系数开始到最低系数,所以我反转了迭代顺序。

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. 我改用List<Int32>更好,它用等于a + 1的固定容量初始化,以便也照顾常数项,一旦所有多项式都被加到索引0定义。

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 . 您的初始值设置为array[0] ,它是数组的未初始化元素,因此值为0 This should instead be set to the highest-order coefficient of the polynomial, ie array[a] . 相反,应将其设置为多项式的最高系数,即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. Horner的方法要求从最高阶系数开始到最低阶。

Implementing the algorithm straight from the Wikipedia article , your loop should instead look like this: 直接从Wikipedia文章实现算法,您的循环应如下所示:

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. 这将产生预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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