2017-10-18 43 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);