2017-10-18 31 views
-1

我正在與C++的任務。基本上我採取雙方,假設他們的較小的一面或斜邊,然後用功能吐出剩餘的一面。看起來很簡單,我99%確定我的數學是正確的功能部分,但我不斷得到奇怪的大答案。代碼來計算畢達哥拉斯定理

#include<iostream> 
#include<cmath> 
using namespace std; 

double otherSideLength(double, double); 

int main() { 
    double a_small_side; 
    double hypotenuse; 
    double swapStore = 0; 
    double otherSide = 0; 
    cin >> a_small_side; 
    cin >> hypotenuse; 
    if(a_small_side == hypotenuse){ 
     cout << "ERROR" << endl; 
     cout << "0"; 
    } 
    if(a_small_side < hypotenuse){ 
     otherSide = otherSideLength(a_small_side, hypotenuse); 
     cout << otherSide; 
    } 
    if(a_small_side > hypotenuse){ 
     swapStore = a_small_side; 
     a_small_side = hypotenuse; 
     hypotenuse = swapStore; 
     otherSide = otherSideLength(a_small_side, hypotenuse); 
     cout << otherSide; 
    } 
} 

double otherSideLength(double a_small_side, double hypotenuse){ 
    //a^2+b^2=c^2, 
    //b^2 = c^2 + a^2 
    //b = sqrt(c^2 + a^2) 
double b = sqrt(pow(hypotenuse, 2) + pow(a_small_side, 2)); 
return b; 
} 

如果有人想快速瀏覽一下,那很棒。

+7

當您移動^ 2到方程的右手側應該是負的。換句話說,當你應該減去^ 2時,你正在添加^ 2。 – csmckelvey

+0

「但我不斷得到奇怪的大答案」 - 比如?小心分享?示例應該是*問題的一部分*。 –

+1

請不要將「已解決」添加到標題中。只要接受幫助你的答案。 –

回答

1

它在我看來像你有一個符號錯誤。

如果你檢查你的代數你會發現,

A^2 + B^2 = C^2

意味着

b^2 = C^2 - A^2。

+0

啊!謝謝! 我是一個巨大的塗料,我明白你花了你的時間來幫助我的愚蠢的錯誤^ - ^ –

2

除了在Drist的答案中已經發現的正確的代數公式之外,代碼中還存在一些問題。

例如,通常將浮點數與簡單的x == y進行比較是錯誤的;最好使用一種「容差」的「模糊」比較。

此外,簡單地應用經典數學公式計算畢達哥拉斯定理是容易出錯的, a*a可能溢出。更好的方法描述here

假設c是斜邊(c > a),可以這樣做:

// b = sqrt(c*c - a*a); 
double r = a/c; 
double b = c * sqrt(1.0 - r*r); 
相關問題