无法使用Math.Sqrt进行循环以获得准确的平均值。想法?

时间:2016-03-21 19:53:43

标签: c# for-loop

所以我的教授希望我们制作一个程序,其中包含一个数字而不是吐出平方根。问题是我们不允许使用Math.Sqrt,否则会有50%的分数惩罚。因此,我使用here ...

中的以下方法
  1. 为sqrt猜一个数字。
  2. 将数字除以猜测。
  3. 平均原始猜测和新猜测。
  4. 将此平均值设为当前猜测值,然后恢复为第2步。
  5. 一旦你这样做了3-4次(或更多?),它应该越来越近,越接近实际的sqrt。

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void calculateSqr_Click(object sender, RoutedEventArgs e)
        {
            decimal wantedSqrt = Decimal.Parse(input.Text); //Takes the number from the textbox, and converts it to an int.
            Random rnd = new Random(); //We're going to pick a random number.
            decimal guess = rnd.Next(1, 100); //Pick a number between 1-100.
    
            for (int i = 0; i <10; i++)
            {
                decimal divHolder = wantedSqrt / guess; //Divide.
                decimal avgVal = (guess + divHolder) / 2; //Average.
                avgVal = guess; //Make the average our new guess.
    
                Console.WriteLine(guess); //Seems like all it does is write the number 10 times.
            }
            string wantedSqrtString = wantedSqrt.ToString();
            MessageBox.Show(wantedSqrtString);
        }
    }
    

    正如您所知,问题出在我的for循环中。我认为它会起作用,它需要想要的Sqrt,潜水它,用猜测平均它,然后新的平均值将成为猜测,它会循环。相反,它只是在输出中重复10次。这里出了什么问题?

1 个答案:

答案 0 :(得分:0)

我在这里修改了你的代码:

    decimal wantedSqrt = Decimal.Parse(input.text); //Takes the number from the textbox, and converts it to an int.
    Random rnd = new Random(); //We're going to pick a random number.
    decimal guess = rnd.Next(1, 100); //Pick a number between 1-100.

    for (int i = 0; i <10; i++)
    {
    decimal divHolder = wantedSqrt / guess; //Divide.
     guess = (guess + divHolder) / 2; //Average.
     //Make the average our new guess.

    Console.WriteLine(guess); //Seems like all it does is write the number 10 times.
    }
    string wantedSqrtString = wantedSqrt.ToString();
    Console.WriteLine(wantedSqrtString);