2017-02-28 56 views
0

您好,我在我的C++程序(毕达哥拉斯定理)之间的某个地方将问题返回给函数,并使用cout获取输出。(C++)返回和函数输出之间的某处出错

例如,如果我将a设置为3,b设置为0,并且c设置为2,则运行程序并观察我的变量时,输出为0或nan。这里是关于变量的更多信息:

pyth_b_1 - (error)在当前上下文中不可用! P_T() - (错误){浮动(浮动,浮动,浮动)} 0x4014ad

代码:

cout<<"Set one value 0 to get answer for that variable \n"; 
     cout<<"Enter number or 0 for 'a': "; 
     cin>>a; 
     cout<<"Enter number or 0 for 'b': "; 
     cin>>b; 
     cout<<"Enter number or 0 for 'c': "; 
     cin>>c; 
     cout<<"You'r answer = "<<p_t(a, b, c)<<endl; 

代码:

float p_t(float a,float b,float c){ 

    if(a == 0 && b != 0 && c != 0){ 
    // 0 equals nothing for parameters 
    cout<<"You chose to find a"<<endl; 
    float pyth_c = (pow(c, 2)) - (pow(b, 2)); 
    float pyth_a = sqrt(pyth_c); 
    return pyth_a; 
    } 
    else if(a != 0 && b == 0 && c != 0){ 
    float pyth_c_1 = (pow(c, 2)) - (pow(a, 2)); 
    float pyth_b_1 = sqrt(pyth_c_1); 
    return pyth_b_1; 
    } 
    else if(a != 0 && b != 0 && c == 0){ 
    float pyth_a_2 = (pow(a, 2)) - (pow(b, 2)); 
    return pyth_a_2; 
    } 

    } 
+0

在情况1中,如果'c' <'b'那么'pyth_c'将是负数。然后你尝试取其平方根。在所有其他情况下也是如此。除了情况3缺少平方根呼叫。这是精简如何使用调试器的完美程序。 –

+1

我建议学习使用调试器。这将使编程无限轻松。 – dandan78

回答

1

那么,根据你的代码,当a == 3,b == 0,c == 2,我们得到:pyth_c = pow(2, 2) - pow(3, 2),什么给4 - 9 == -5。你不能取那个负数的平方根(至少是实数)。

+0

非常感谢。我重写了我的代码,只允许正数,如果不是,则重新启动程序。再次感谢。 – laquishabonquiquithe3rd