[prog] switch statement
Wolf Rising
wolfrising at gmail.com
Thu Dec 16 17:07:41 EST 2004
Hi,
Thank you for responding :-)
When I run the code with the changes below I get this print out:
Enter the product number (enter 0 to end): 1
Enter the quantity of this product you wish to order: 2
Enter the product number (enter 0 to end): 0
INCORRECT NUMBER ENTERED. PLEASE TRY AGAIN.
The total sales in dollars is: 5.96
How would I adjust it without the if statement to prevent the
INCORRECT NUMBER ENTERED
PLEASE TRY AGAIN from appearing?
On Thu, 16 Dec 2004 15:35:00 +1100, Jacinta Richardson
<jarich at perltraining.com.au> wrote:
> The if statement isn't required, and personally I'd leave it out. This
> can be done with the following changes:
>
> > #include <iostream>
> > using namespace std;
> >
> > int main() {
> >
> > //define variables
> > int product; // product to be ordered
> > int quantity;//quantity to be ordered
> > double price;
> > double totalSales;
> >
> >
> > // Get input from user
> >
> > do {
> > product = 0;
> > //order product desired by product number
> > cout << "Enter the product number (enter 0 to end): ";
> > //receive product number
> > cin >> product;
> >
> >
> > //begin switch statement, define prices of product by number
> > switch ( product) {
> > case 0:
> > break;
> >
> > case 1:
> > price = 2.98;
> > break;
> >
> > case 2:
> > price = 4.50;
> > break;
> >
> > case 3:
> > price = 9.98;
> > break;
> >
> > case 4:
> > price = 4.49;
> > break;
> >
> > case 5:
> > price = 6.87;
> > break;
> >
> > default:
> > cout << "INCORRECT NUMBER ENTERED. PLEASE TRY AGAIN. \n";
> continue; /* Restart the loop */
> >
> > }
> >
>
> // If we reach here, we must have valid input.
> > //order quantity of product desired
> > cout << "Enter the quantity of this product you wish to order: ";
> > //receive quantity
> > cin >> quantity;
> >
> > //calculate total
> > totalSales += quantity * price;
> >
> > }while (product != 0);
> >
> > cout << "The total sales in dollars is: " << totalSales;
> >
> > return 0;
> > }
>
> My rationalisation for this is that if you go and add another case in,
> you don't have to update the if statement. It also assists in avoiding
> the case where you have cases 1-5 and 7, 9, but 6 and 8 are invalid (for
> some spurious reason).
>
> This should always work unless I've forgotten something about calling
> continue for a loop from a switch statement....
>
> All the best,
>
> Jacinta
>
> --
> ("`-''-/").___..--''"`-._ | Jacinta Richardson |
> `6_ 6 ) `-. ( ).`-.__.`) | Perl Training Australia |
> (_Y_.)' ._ ) `._ `. ``-..-' | +61 3 9354 6001 |
> _..`--'_..-_/ /--'_.' ,' | contact at perltraining.com.au |
> (il),-'' (li),' ((!.-' | www.perltraining.com.au |
>
> _______________________________________________
> Programming mailing list
> Programming at linuxchix.org
> http://mailman.linuxchix.org/mailman/listinfo/programming
>
More information about the Programming
mailing list