繁体   English   中英

C ++精确求平方根

[英]C++ Finding square roots to a precision

这是我第一次使用C ++,我的作业分配如下,并在下面进行尝试。

  • 您将要编写一个程序,该程序将计算出所需精度的平方根。 通过提示用户输入两个数字来开始程序:(1)要确定其平方根的值,以及(2)结果中所需精度的小数位数。 使用循环分别确定下一个最高的正平方和下一个最低的正平方。 然后应构建一个计数控制的循环; 它将对每个所需的小数位执行一次;
  • 在此计数控制循环的单次通过期间,近似值将递增或递减Δ= 1 / 10decimalPosition,直到通过实际值为止。 在循环的第一遍,Δ将为1/10 1 = 0.1; 在第二遍时,Δ将为1/10 2 = 0.01,依此类推。 如果近似值太小,则计数控制循环中的事件控制循环将使近似值递增,直到变得太大为止。

我不确定如何开始为第2段中的过程构建循环。尽管有指示,但它们对我来说没有意义。

到目前为止,我的进度:

int
sqroot()
{
   cout << setiosflags (ios::fixed|ios::showpoint); //assumed I need for output  later


   double number;
   cout<<"Enter the number to find the square root of: ";
      cin>>number;
   int sqRoot = 1;            
   while (sqRoot*sqRoot < number)   // sqRoot is too small
      sqRoot++;                     //  try the next number

   int y=0;
   int newRoot =1;
   while (y < number)
  {
     if (newRoot*newRoot > number )
     break;
     y=newRoot*newRoot;
     newRoot++;
  }


    int decimalInput;
    int decimalPosition= 0;
       cout<<"Enter the desired decimal position: "<<endl;
       cin>>decimalInput;
    while (decimalPosition < decimalInput)
        decimalPosition++;

    return 0;

 }

您不仅应该将新的newRoot递增1(newRoot ++),而且应以较小的步长递增。 为了提高效率,您可以开始大步(10的幂次方,例如1000)。在结果的平方大于输入数之前,将该步除以10。

额外提示:

有两个嵌套循环。 外循环检查步骤> =错误,内循环检查结果是否足够小。

暂无
暂无

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

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