简体   繁体   中英

Function not returning a value (C++)

I'm very new, so forgive the newbie question. I've tried compiling the code, it runs but does not return a value after the radius (r) has been entered. When I change the function to a type Void and use cout, it works. I'd like to have it work with the regular type double function. Also as a side question, my question to try it again doesn't work if I try to opt out. ie by entering n, instead of y.

double const pi=3.1415;
double r=0.0;
char ans;

do {
    cout << "Please enter in the radius\n";
    cin >> r;

    area(pi, r);
    circumference(pi, r);

    cout << "Would you like to try again?\n";
    cin >> ans;

} while (ans=='y'||'Y');



return 0;
}

double area(double pi, double r)
{
double area_2=(pi*pow(r,2));
return area_2;

}

double circumference(double pi, double r)
{

double circumference_2=(2*pi*r);
return circumference_2;

}

In simple terms, your functions are written to return a value (double), they do not inherently print anything.

Either use:

cout << area(pi, r);

or cout in the function itself. Hope that helps.

The logical or operator works like this: Lets say we have A || B A || B then the result if true if A is true, or B is true.

And since in C++ everything non-zero is true your condition ans=='y'||'Y' is basically equivalent to ans=='y'||true . In other words, it's always true. Which in turn mean you have an infinite loop.

You want ans == 'y' || ans == 'Y' ans == 'y' || ans == 'Y' instead.

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