I am having trouble structuring my programs, with cascading if statements and nested if statements. This program adds subtracts multiplys and divides. But you have to enter a or A for addition. S or s for subtraction, and so on. If you don't enter a correct letter the program should output INPUT ERROR. Also when subtracting, the smaller number should always be subtracted from the larger. Divison the larger number will always be divided by the smaller.
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
// Declaring Varibles.
char method = ' ';
float first, second;
int add, sub, div, multi ;
cout<<"Please enter the method of factoring you would like to use,"<<endl;
cout<<"(A = Addition),(S = Subtraction),(D = Divide),(M = Multiply)"<<endl;
cin>> method;
method = toupper(method);
if (method == 'A' || 'a')
{
cout<<"Please enter the first number"<<endl;
cin>>first;
cout<<"Please enter the second number"<<endl;
cin>>second;
add = first + second;
cout<<"The total is:"<<add<<endl;
}
elseif (method == 'M' || 'm')
{
cout<<"Pleae enter the first number"<<endl;
cin>>first;
cout<<"Please enter the second number"<<endl;
cin>>second;
multi = first * second;
cout<<"The total is:"<<multi<<endl;
}
elseif (method == 'S' || 's')
{
cout<<"Please enter the first number"<<endl;
cin>>first;
cout<<"Plese enter the second number"<<endl;
cin>>second;
if (second > first)
sub = first - second;
else
sub = second - first;
cout<<"the total is:"<<sub<<endl;
}
elseif (method == 'D' || 'd')
{
cout<<"Please enter the first number"<<endl;
cin>>first;
cout<<"Plese enter the second number"<<endl;
cin>>second;
if ( second > first)
div = second / first;
else
div = first / second;
cout<<"The total is:"<<div<<endl;
}
else
cout <<"Input Error"<<endl;
}
return (0);
}
The only issue I see with the structuring is your somewhat inconsistent spacing. You should work on lining up the code based on how many brackets deep it is.
Doesn't matter, you've already done the correct thing but using "toupper()", see my edit in the previous post. But to answer you question, yes, that is the only way to do it because those logical evaluations work on the result of the operations on either side of them.