简体   繁体   中英

(c++) Error somewhere between return and function output

Hello I am having a problem in my C++ program (pythagorean theorem) somewhere in between returning my value to the function and getting the output using cout.

For example if I set a to 3, b to 0, and c to 2, when running the program and watching my variables, the output is either 0 or nan. Here is more info on the variables:

pyth_b_1 - (error) Not available in current context! p_t() - (error) {float (float, float, float)} 0x4014ad

Code:

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;

Code:

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;
    }

    }

Well, according to your code, when a == 3, b == 0, c == 2, we get: pyth_c = pow(2, 2) - pow(3, 2) , what gives 4 - 9 == -5 . You can't take square root of that negative number (in real numbers at least).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM