This is for a class assignment that I have been unable to figure out. I know it can be done using if and else statements but my instructor wants it figured out using specifically the SWITCH statement.
*Write a program that uses a switch statement to evaluate the following function:
x^{2} ; x <= 3
cos(x) ; 3 < x <= 6
ln(x) ; 6 < x < 20
sqrt(x) ; x >= 20
#include <iostream>
#include <cmath>
usingnamespace std;
int main ()
{
double x;
cin >> x;
switch ( x <= 3 )
{
case 1:
cout << x * x << endl; //when x is less than or equal 3 it squares x
break;
default:
cout << sqrt(x) << endl; //when x is 20 it square roots the function
break;
}
system ("pause")
return 0;
}
This is similar to what I compile, i do use the cin >> x; as well and do have a basic understanding of the math functions and C++ layout, I am also assuming that what my instructor wants is something involving recursion as well. I was also thinking of trying to call the functions using void and call them in the main() body. Any feedback is appreciated, thanks.
I know it does seem impractical to use the switch this way but I cannot think of a way to apply the loop continuation conditions to shorten it. I was able to get it to work using static_cast<int> for the testing value in my switch. If interested I will try to post my instructors method of the solution. I appreciate the help, thanks!!