C#逻辑(编码中需要的解决方案)

强尼

我想使用如下循环:例如,我在公式中的文本框123和300中放入了示例。

1/2 *(300 + 123/300)= 150.205 >>回答

我想循环此示例,我得到了答案150.205,下一个公式应如下所示

1/2 *(150.205 + 123 / 150.205)= 75.512

这个方程的答案我想循环输入下一个公式。

我已经编写了代码,但我不知道如何通过循环使用它

我的代码。

double value = (0.5 * (300 + 123 / 300));

======================================

对于结束循环

当条件匹配像这样1/2 *(11.091 + 123 / 11.091)= 11.091含义答案和输入相同,即输入300将相同,我想中断循环

**Example** I want to do this without using square root function in c# 
    like simple if i want a root of 9 it will be 3 so it will be like this .
    i choosen 1 Because 9 is one value so i choosen 1
    1/2*(1+9/1) = 5.000
    1/2*(5+9/5) = 3.400
    1/2*(3.4+9/3.4)  =   3.024 
    1/2*(3.024+9/3.024) = 3.000
    1/2*(3+9/3) = 3.000 
    see you will get same value in one point  always
德米特里·拜琴科(Dmitry Bychenko)

唯一棘手的事情是将公差公差进行比较,因为由于舍入误差,您可能永远无法满足

  answer == value

状况。实现可能是

  double answer = 300.0;
  double tolerance = 1e-10;

  while (true) {
    // based on previous answer we compute next one
    double value = 0.5 * (answer + 123.0 / answer);

    //TODO: you can print out steps here, if you want something like this
    //Console.WriteLine(value);  

    // check convergence with tolerance 
    if (Math.Abs(answer - value) <= tolerance) {
      answer = value;

      break;
    }

    // next answer (value) becomes the previous one (answer)
    answer = value;
  }

  // 11.0905365064094
  Console.Write(answer); 

实际答案(证明)仅是平方根

  // 11.09053650640941716205160010261...
  Console.Write(Math.Sqrt(123));

现实生活中的实现(如果老板希望我实现):

public static double NewtonEstimation(Func<double, double> function, 
                                      double tolerance = 1e-10, 
                                      double guess = 1.0) {
  if (null == function)
    throw new ArgumentNullException("function");
  else if (tolerance < 0)
    throw new ArgumentOutOfRangeException("tolerance", "tolerance must not be negative");

  while (true) {
    double value = function(guess);

    if (Math.Abs(value - guess) <= tolerance)
      return value;

    guess = value;
  }
}

...
// 11.0905365064094
Console.Write(NewtonEstimation(x => 0.5 * (x + 123 / x)));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

需要解决方案来删除 C# 中的重复代码

需要帮助来了解Ruby气泡排序解决方案中的语法/逻辑

验证解决方案逻辑时需要的建议

需要一个简单的编程逻辑解决方案。

解决方案文件中的C#项目名称

C#查找解决方案中的所有测试

大型C#解决方案中的配置文件

如何在C#项目(解决方案)中找到所有硬编码值?

以下c / c ++解决方案的逻辑说明

限制 C# 功能的解决方案

C# FizzBuzz 开关解决方案

Google Foobar:次优解决方案中的逻辑错误

在HaxeFlixel中编码资产的最佳解决方案

了解 c 中的背包解决方案

C ++中多重定义的解决方案

C# - 解决潜在的死锁解决方案

需要解决方案C ++循环和条件

有没有一种方法可以确定Visual Studio C#解决方案中的哪些功能需要管理员权限

大量的C / C ++ / Java / C#递归解决方案

如何在C#解决方案中引用其他文件夹中的文件

在Visual Studio C#中开发WebService,然后从单独的VS解决方案中调用它

C ++ / C#解决方案中不可用的任何CPU

从C#中运行调试器获取解决方案详细信息

如何使用roslyn删除c#解决方案中源代码的所有注释?

C#解决方案始终检查系统中的特定条件

在一个解决方案中从 VB 项目调用 C#

在C#中以指定间隔生成数字-最佳解决方案

使解决方案中的每个csproj都针对不同的C#版本

将具有本地Dll的C#解决方案部署到单个EXE中