I am trying to switch this if...else statement to a Switch and I can not get the program to calculate. Please help?

original if, else

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::setw;


int main ()
{

	int x, total=21;
	cout << "Input Number for X:  ";
	cin >> x;


total = 21;
if (x == 1)
    total += 2;
else
    if ((x > 1) && (x < 5))
          total *= 3;
    else
        if (x == 6)
            total = 47;
        else
            total = 4*x + 3;
cout << total << endl
 
     return 0; 
}// end main

and the switch statment that is not calculating

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::setw;


int main ()
{

	int x, total=21;
	cout << "Input Number for X:  ";
	cin >> x;

		switch(x)
		{
			case'1':
				total += 2;
				break;
			case '2':
				 total *= 3;
				break;
			case '3':
				 total *= 3;
				break;
			case '4':
				 total *= 3;
				break;
			case'6':
				total = 47;
				break;
			case '5':
				 total = 4*x + 3;
				 break;
		}

				 cout << total << endl;

			return 0;
		}

Thanks,
m

Recommended Answers

All 3 Replies

remove the single quotes from around the digits in the case statements. What you have are chars not ints. x is an int so use ints.

case 1:

not

case '1':

Never mind I figured out my mistake! Thanks!

Thank you Lerner! After looking at it I knew where I had gone wrong! It's like calling a repair man, the thing is fixed before he gets there. Thanks again!
M

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.