簡體   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