2012-02-15 41 views
0

這是我第一次使用C++,我有如下作業分配,下面有一個嘗試。C++發現平方根到精度

  • 你要編寫一個程序來計算平方根到所需的精度。通過提示用戶輸入兩個數字來開始程序:(1)確定平方根的值和(2)結果中所需精度的小數位數。使用循環分別確定下一個最高完美平方和下一個最低完美平方。然後應該構建一個計數控制的循環;它會爲每個所需的小數位執行一次;
  • 在此計數控制循環的單次通過期間,近似值將增加或減少Δ= 1/10decimalPosition,直到實際值通過。在循環的第一遍中,Δ將爲1/10 = 0.1;在第二次通過時,Δ將是1/10, = 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; 

} 
+1

如果你真的想要一個A,添加相對錯誤檢查這個參考http://en.wikipedia.org/wiki/Methods_of_computing_square_roots – pyCthon 2012-02-15 02:19:45

回答

0

你不應該僅僅由1(newRoot ++),而是由更小的步驟增加新newRoot。爲了使它更有效率,你開始白步大步(10的大功率,例如1000)。在結果的平方比輸入的數字更大之前,將該步驟除以10。

額外提示:

有兩個嵌套循環。外循環檢查step> = error,內循環檢查結果是否足夠小。

+0

所以像'code'newRoot = 1000 newRoot + = .1 – PrimateVariant 2012-02-15 01:12:11