Basically I have this calculator program, and its going very well except one problem when using a switch statement.
This is my code, and whenever I use a switch statement OUTSIDE of int main() {}
it won't work and will just logout as soon as it runs the switch statement. As I said the one in int main works but for example in the area() {} function it wont work? I was wondering if anyone could help me solve this.
P.S If I try using an if statement it works as you can see in one of my functions however I think its best using a switch statement and I would like to know whats wrong for future reference.
#include <iostream>
#include <math.h>
usingnamespace std;
int One;
int Two;
int choose;
void area() {
cout << "Type one to find the area of a triangle, two to find the area of a square, three to find the area of a rectangle and four to find the area of a circle. ";
switch (choose) { // It won't work here though?
case 1:
cout << "Please enter the base length of the triangle, followed by the height. ";
cin >> One >> Two;
cout << "The area of the triangle is" << "t" << One / 2 * Two;
break;
case 2:
cout << "Please enter the length of one of the sides of the square please. ";
cin >> One;
cout << "The area of the square is" << "/t" << One * 2;
break;
case 3:
cout << "Please enter the length of the rectangle, followed by the height. ";
cin >> One >> Two;
cout << "The area of the rectangle is " << "/t" << One * Two;
break;
case 4:
Two = 3.14;
cout << "Please enter the radius of the cirlce please. ";
cin >> One;
cout << "The area of the cirlce is" << "/t" << Two * One * One;
break;
}
}
void powers() {
float power;
cout << "Please enter 1 for powers and 2 for square roots. ";
cin >> choose;
if (choose == 1) { // If statement works here rather than switch
cout << "Please enter the number you would like to square and the number /nof times you would like to times it by it. ";
cin >> One >> Two;
cout << "\t" << pow(One, Two);
}
if (choose == 2) {
cout << "Enter a number to find its square route. ";
cin >> power;
cout << "\t" << sqrt(power);
}
}
void division() {
cin >> One >> Two;
cout << "\t" << One / Two;
}
void multiplication() {
cin >> One >> Two;
cout << "\t" << One * Two;
}
void addition() {
cin >> One >> Two;
cout << "\t" << One + Two;
}
void subtraction() {
cin >> One >> Two;
cout << "\t" << One - Two;
}
int main () {
system ("clear");
cout << "Press one for subtracting, two for adding, three, multiplication and four for division, five for powers and six for area.";
cin >> choose;
switch (choose) { // Works here
case 1:
subtraction();
break;
case 2:
addition();
break;
case 3:
multiplication();
break;
case 4:
division();
break;
case 5:
powers();
break;
case 6:
area();
break;
}
return 0;
}