For a class project I have to develop a program that calculates the cost of a mobile device service. There are 3 packages the user can choose from. The cost of the service is determined by the base price and number of message units to be used. After the user chooses a package I have to let them know the price of the package as well as letting them know if either of the other packages would be cheaper and show what the difference in price would be by using switch statements. I've wrote some switch statements comparing the packages, but how do I show and calculate how much they would save if there is a cheaper package than the one chosen? I am also a beginner so take it easy.
int main() {
bool finished = false;
do {
// to keep it simple
double choice_a = 9.95;
double choice_b = 19.95;
double choice_c = 39.95;
char choice;
int message_units;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice;
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
// user enters how many units is wanted
cout << "How many message units (enter 1 - 672)" << endl;
// again check this (if homework requires checking input)
cin >> message_units;
// Calculating message units
if(message_units > 5){
price += 100 * (message_units - 5);
}
if(message_units > 15){
price += 50 * (message_units - 15);
}
// Total Price Output
cout << "Your total cost is " << price/100 << endl
// Is user done?
char done;
cout << "Do you want to enter another? press enter to continue.
cin >> done;
// check
if (done != ' ') {
finished = true;
}
}
while (finished = false);
}
switch (choice)
{
case 'A':
if(choice_b < choice_a);
cout << "You can save by switching to package B" << endl;
else if(choice_c < choice_a);
cout << "You can save by switching to package C" << endl;
break;
case 'B':
if(choice_a < choice_b);
cout << "You can save by switching to package A" << endl;
else if(choice_c < choice_b);
cout << "You can save by switching to package C" << endl;
break;
case 'C':
if(choice_a < choice_c);
cout << "You can save by switching to package A" << endl;
else if(choice_b < choice_c);
cout << "You can save by switching to package B" << endl;
break;
}
#include <iostream>
using namespace std;
int main() {
bool finished = false;
char choice;
double choice_a = 9.95;
double choice_b = 19.95;
double choice_c = 39.95;
int message_units;
double price;
bool selected = false;
do {
// to keep it simple
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice;
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
// user enters how many units is wanted
cout << "How many message units (enter 1 - 672)" << endl;
// again check this (if homework requires checking input)
cin >> message_units;
// Calculating message units
if(message_units > 5){
price += 100 * (message_units - 5);
}
if(message_units > 15){
price += 50 * (message_units - 15);
}
// Total Price Output
cout << "Your total cost is " << price/100 << endl;
switch (choice)
{
case 'A':
if(choice_b < choice_a)
cout << "you can save by switching to package B it saves: " << choice_a - choice_b << " if you choose B" << endl;
else if(choice_c < choice_a)
cout << "You can save by switching to package C is saves: " << choice_a - choice_c << endl;
break;
case 'B':
if(choice_a < choice_b)
cout << "you can save by switching to package A it saves: " << choice_b - choice_a << " if you choose a" << endl;
else if(choice_c < choice_b)
cout << "you can save by switching to package C it saves: " << choice_b - choice_c << " if you choose c" << endl;
break;
case 'C':
if(choice_a < choice_c)
cout << "you can save by switching to package A it saves: " << choice_c - choice_a << " if you choose a" << endl;
else if(choice_b < choice_c)
cout << "you can save by switching to package A it saves: " << choice_c - choice_b << " if you choose b" << endl;
break;
}
// Is user done?
char done;
cout << "Do you want to enter another? press enter to continue.";
cin >> done;
// check
if (done != ' ') {
finished = true;
}
}
while (finished == false);
}
sorry for not explaining but i try explaining it the best i can
based on your code. i fix some wrong syntaxe and tries to match the problem
you've post so i defined all the variables you've created outside the first
outer bool so that the switch statement will work and i edit some code in the switch statement to calculate the amount of savings and displays them based on the conditions sorry for bad english.
Assuming you are comparing the two with the same quantity,
Savings = [(Selection Price) - (Cheaper Option Price)]× Quantity
If you do this calculation and say assign it to a type double called Savings, you can print this out.
cout << "Savings are "<< Savings;
Doing this on each if statement is simple, but of course there are better ways to do this. Such as calling a function that does this simple calculation for two options.
EDIT 1: Apologize for the poor formatting, this is on my phone.
EDIT 2: Also noticed you have incorrect syntax with your control loops. Here is a good resource here
EDIT 3: There are actually a number of other issues including your switch statement being outside of main.
This line doesn't make sense, in practical terms.
// Calculating message units if(message_units > 5){ price += 100 * (message_units - 5); } if(message_units > 15){ price += 50 * (message_units - 15); }
Good practice would suggest not overwriting a variable with a value with a different meaning. It is confusing. Initially it seems price is the per quantity price. Then it looks like you try to assign the overall cost to it.
(I'm assuming; it doesn't actually do this. Instead it adds a price of 100 per unit except for the first 5 to a single unit price you declare at the top. Similarly for the greater than 15 block.)
EDIT 4: Per request in comments:
If I am correct in what I think you are trying to do, replace this block:
// Calculating message units
if(message_units > 5){
price += 100 * (message_units - 5);
}
if(message_units > 15){
price += 50 * (message_units - 15);
}
with:
double Total_Cost;
if(message_units => 5 && message_units<15){
Total_Cost = price * (message_units - 5);
}
else if(message_units => 15){
Total_Cost = price * (message_units - 15);
}
else{
Total_Cost = price * message_units;
}
That is 'you get the first 5 free (or 15) if you buy in bulk'. Otherwise it is just the price times the number of units. This again seems kind of strange, but this is what this does.
Related
How do I get the variable total to get each price every time the program loops? The expected values is the total for every number input added together and each number has a specific value. I don't get any output when the number 8 is input, which is supposed to print and end the loop.
#include <iostream>
using namespace std;
int main() {
int option;
double one = 17.50;
double two = 12.95;
double thre = 11.56;
double four = 7.99;
double five = 15.00;
double six = 9.99;
double total = 0;
do{
cout<<"**************************************BRAINS!**************************************"<<endl;
cout<<"**************************************Menu**************************************"<<endl;
cout<<"1) Thalamustard-Crusted Filet - $17.50"<<endl;
cout<<"2) Hypothamoussaka - $12.95"<<endl;
cout<<"3) Amyg-DAL-a - $11.56"<<endl;
cout<<"4) CHIPpocampus & Dip- $7.99"<<endl;
cout<<"5) Pons Pasta Special - $15.00"<<endl;
cout<<"6) Medulla Frittata - $9.99"<<endl;
cout<<"7) Finish Current Sale + Start a New Sale"<<endl;
cout<<"8) Quit Forever - APOCALYPSE"<<endl;
cin>>option;}
while ( option <= 8 && option > 0);
while(option <= 0){
if (option == 1){
double total = total + one;
}
else if (option == 2){
double total = total + two;
}
else if (option == 3){
double total = total + thre;
}
else if (option == 4){
double total = total + four;
}
else if (option == 5){
double total = total + five;
}
else if (option == 6){
double total = total + six;
}
else if (option == 7){
double total = total + (total*0.06);
}
else{
cout<<"HURRY UP!";
}
if (option == 8){
cout<<"Your total is: $"<<total; //This does not print or accumulate
}
}
}
Every time you are creating a new local total variable in the lines
double total = total + one;
and it is not changing the actual total value. Changing this line to
total += one; //or two....
can solve this issue.
Why your Code not working
look at the code equivalent
do{
// print measseges
cin>>option;
} while (option <= 8 && option > 0);
while(option<=0){
// decode the option meaning
}
the code will circular in the first loop (printing msg and get an input) and exit the loop when the option variable greater then 8 or a nigitive value
if first loop end with option is positve (greater then 8) then the second loop will never excuited and the program will termenate without any response !!
the second loop will only excuit when option varible is negative value ... and in this case , that will make an infinity loop >>> only the else statment will excuite for ever.
so you have two main error here
the option in the second loop (if first loop termentate with negative value)is always negative so non of your if statment check has meaning
you declare Total variable multible times
and those problem could be solved by the follwing code :
#include <iostream>
using namespace std;
int main() {
int option;
double one = 17.50;
double two = 12.95;
double thre = 11.56;
double four = 7.99;
double five = 15.00;
double six = 9.99;
double total = 0;
do {
cout << "**************************************BRAINS!**************************************" << endl;
cout << "**************************************Menu**************************************" << endl;
cout << "1) Thalamustard-Crusted Filet - $17.50" << endl;
cout << "2) Hypothamoussaka - $12.95" << endl;
cout << "3) Amyg-DAL-a - $11.56" << endl;
cout << "4) CHIPpocampus & Dip- $7.99" << endl;
cout << "5) Pons Pasta Special - $15.00" << endl;
cout << "6) Medulla Frittata - $9.99" << endl;
cout << "7) Finish Current Sale + Start a New Sale" << endl;
cout << "8) Quit Forever - APOCALYPSE" << endl;
cin >> option;
if (option == 1) {
total = total + one;
}
else if (option == 2) {
total = total + two;
}
else if (option == 3) {
total = total + thre;
}
else if (option == 4) {
total = total + four;
}
else if (option == 5) {
total = total + five;
}
else if (option == 6) {
total = total + six;
}
else if (option == 7) {
total = total + (total * 0.06);
}
else if (option == 8) {
cout << "Your total is: $" << total;
breack;
}
else {
cout << "not valied input";
}
} while (option <= 8 && option > 0);
}
code tips for better Reading
you could encapsulate the printing menue in another function
use switch statment rather than if it will make it much more
cleaner to read
do while is suck use while loop with true condition at first
you coude use array rather than discret variable for saving constant
look for the next code it much more beautiful after apply this simple tricks
#include <iostream>
using namespace std;
void printMenu();
int main() {
int option =0;
double one = 17.50;
double two = 12.95;
double thre = 11.56;
double four = 7.99;
double five = 15.00;
double six = 9.99;
double total = 0;
cout << "**************************************BRAINS!**************************************" << endl;
while(option != 8)
{
printMenu();
cin >> option;
switch (option)
{
case 1:total += one;break;
case 2:total += two;break;
case 3:total += thre;break;
case 4:total += four;break;
case 5:total += five;break;
case 6:total += six;break;
case 7:
cout << "Your total is" << total << " $\n starting new sale ... \n";
total =0;
break;
case 8:
cout << "Your total is: " << total << " $ \n"<<"End of the program";
break;
default:
cout << "you entered "<<option<<"and this is not a valid option please try agian\n";
break;
}
}
}
void printMenu() {
cout << "**************************************Menu**************************************" << endl;
cout << "1) Thalamustard-Crusted Filet - $17.50" << endl;
cout << "2) Hypothamoussaka - $12.95" << endl;
cout << "3) Amyg-DAL-a - $11.56" << endl;
cout << "4) CHIPpocampus & Dip- $7.99" << endl;
cout << "5) Pons Pasta Special - $15.00" << endl;
cout << "6) Medulla Frittata - $9.99" << endl;
cout << "7) Finish Current Sale + Start a New Sale" << endl;
cout << "8) Quit Forever - APOCALYPSE" << endl;
}
I need help. I'm currently learning C++ programming and I'm still at the beginner level. I'm still figuring out how to make the while loop working. My idea is when inserting the correct code input, the switch statement choose the right case statement and loop back to insert another input until 0 inserted to stop the loop and calculate for the final output in main() constructor.
I know I have few kinks to fix soon but I'm still struggling to figure out this particular part.
#include <stdio.h>
#include <iostream>
#include <iomanip>
using namespace std;
double sst = 0.06, total = 0, grandTotal, price, discount, newPrice, totalSST;
int quantity, count, code;
string name, ech;
void item001(){
name = "Rice (5kg)";
price = 11.5;
discount = 0;
}
void item002(){
name = "Rice (10kg)";
price = 25.9;
discount = 0;
}
void item003(){
name = "Sugar (1kg)";
price = 2.95;
discount = 0;
}
void item_cal(){
cout << "Please enter the quantity of the item: ";
cin >> quantity;
newPrice = (price + (discount * price)) * quantity;
cout << "\nItem: " << name << " || Quantity: " << quantity << " || Price: RM" << newPrice << endl;
}
void input(){
cout << "Welcome SA Mart\n" << "Please insert the code. Press 0 to stop: ";
while (code != 0){
cin >> code;
switch (code){
case 001:
item001();
item_cal();
break;
case 002:
item002();
item_cal();
break;
case 003:
item003();
item_cal();
break;
default:
cout << "\nWrong code" << endl;;
break;
total += newPrice;
}
}
}
int main(){
input();
totalSST = total * sst;
grandTotal = total + totalSST;
cout << fixed << setprecision(2);
cout << "Total: RM" << total << " ||SST: RM" << totalSST << " || Grand Total: RM" << grandTotal << endl;
return 0;
}
The only functional issue I see in your code is that there is a chance that the code variable will initialize to 0 (depends on the compiler/randomness). If that happens, your input method will return before it enters the loop. Other than that it looks like it will work. Of course, programming is not just the art of "making it work," style and readability are important too. In general, you want to confine variables to the smallest scope in which they are referenced. 'code' should not be a global variable, it should live in the input method. As for the loop, there are several ways it could be implemented: a "while(true)" loop could be used, in which case the variable may be defined inside the loop; on the other hand a "do while" would guarantee one loop runs (perhaps that would be a good fit here), but the variable must live outside of the loop, at least int the scope of conditional check. The way you choose is often a matter of style. Below, I use a "while(true)."
In programming, readability matters (a lot). I think this program would be easier to read if the data were broken up into a few structs, perhaps "Bill," and "Food." Another thing to consider is how to broaden the usage of your program, without introducing significant complexity. For example, it could work for any grocery store (any set of food items/prices). This is often a matter of determining an appropriate set of parameters to feed your program.
To do these things you might write something like this:
#pragma once
#include <string>
#include <map>
using namespace std;
namespace market {
const double& sst = 0.06;
struct Bill {
double total = 0;
double totalSST = 0;
double grandTotal = 0;
};
struct Food {
const char* name;
double price;
double discount;
Food(const char* name, double price, double discount = 0)
: name(name), price(price), discount(discount) {}
double result_price() const {
return price - price * discount;
}
};
struct GroceryStore {
const char* name;
std::map<int, Food> inventory;
GroceryStore(const char* name, std::map<int, Food> inventory)
: name(name), inventory(inventory) { }
};
void shop(const GroceryStore& store, Bill& bill, bool show_menu = false, int exit_code = 0) {
// check error conditions
if (store.inventory.find(exit_code) != store.inventory.end()) {
// that's the 'exit_code' code silly!
cout << "Bad store. Come back another time." << endl;
return;
}
cout << "Welcome to " << store.name << endl;
if (show_menu) {
cout << "The following items are available for purchase:" << endl;
for (auto p : store.inventory) {
cout << "\t" << p.first << ") " << p.second.name << "(" << p.second.result_price() << endl;
}
}
cout << "Enter the product code of the item you wish to purchase:";
int code;
cin >> code;
while (true) {
auto food_it = store.inventory.find(code);
if (food_it == store.inventory.end()) {
cout << "Thanks for stopping by." << endl;;
break;
}
cout << "Please enter the quantity of the item: ";
uint32_t quantity;
cin >> quantity;
auto& food = food_it->second;
auto disc_price = food.price - (food.discount * food.price);
bill.total += disc_price * quantity;
cout << "\nItem: " << food.name << " || Quantity: " << quantity << " || Price: RM" << disc_price << endl;
cout << "Would you like anything else? Enter the product code, or press " << exit_code << " to proceed to check-out." << endl;
cin >> code;
}
}
void ring_up(Bill& bill) {
bill.totalSST = bill.total * sst;
bill.grandTotal = bill.total + bill.totalSST;
}
void run() {
int code = 1;
GroceryStore store("SMart", {
{ code++, Food("Rice (5kg)", 11.5, 0) },
{ code++, Food("Rice (10kg)", 25.9) },
{ code, Food("Sugar (1kg)", 2.95, 0) }
});
Bill bill;
shop(store, bill, true);
ring_up(bill);
cout << "Total: RM" << bill.total << " ||SST: RM" << bill.totalSST << " || Grand Total: RM" << bill.grandTotal << endl;
}
}
Firstly there is a bug in input when u will input 0 then also it won't break while loop as code that is checked contains the previous value.
for example:
input is
3
0
but according to your code when the code will run the second time and while condition is checked code still contains 3 as value and code will run one more time
Try initialising code to some value, for example, -1. I'm not really sure but I think for global int variables, they initialise int variables to 0. So your first loop doesn't run. Or another way to do it is using do while loops instead of while loop.
do {
cin >> code;
switch (code){
case 001:
item001();
item_cal();
break;
case 002:
item002();
item_cal();
break;
case 003:
item003();
item_cal();
break;
default:
cout << "\nWrong code" << endl;;
break;
total += newPrice;
} while (code != 0);
}
This makes sure that the loop will run at least once, making code initialised.
Hope it helps you! Have fun programming!
So for a program I'm writing I have a menu the user can enter an integer choice to calculate a few different things. Choice 1-4 are calculations, 5 should call a function to print data from a file to the console, and 6 quits everything. For whatever reason after adding a new case (5) to the switch statement I had, my code has kind of broken. When I enter 5 the program still asks me to enter a weight (which I don't understand at all), after which it will enter an infinite loop, which means it has to have made it into the while loop in my print() function. I don't understand what the hell is going on so I would really appreciate a second set of eyes.
int main()
{
srand(time(0));
bool repeat = true;
bool loopFlag = true;
float calories = 0;
string intensity = "";
cout << "Welcome to Carmello's Fitness Center" << endl;
do // main loop
{
fstream transactionLog;
transactionLog.open("userfile.txt", std::ios::in |std::ios::out |std::ios::app);
int idNum;
menu(idNum); // simply displays the menu
loopFlag = true;
int choice = userChoice(choice, loopFlag); // gets the users menu choice
loopFlag = true; // this resets the loopflag to ensure it can be used again after the last validation
float weight = userWeight(weight, loopFlag); // gets users weight and converts into kilograms for further calculations
float weightPoundsCopy = weight;
weight = weight / 2.2;
int time = 0;
float calories = 0;
switch (choice)
{
case 1:
{
int lower = 30, upper = 60;
int activity = BIKING;
string description = "riding the stationary bike: ";
met(weight, loopFlag, activity, lower, upper, description, time, calories, intensity);
break;
}
case 2:
{
int lower = 30, upper = 60;
int activity = RUNNING;
string description = "running on the treadmill: ";
met(weight, loopFlag, activity, lower, upper, description, time, calories, intensity);
break;
}
case 3:
{
int lower = 15, upper = 30;
int activity = LIFTING;
string description = "lifting weights: ";
met(weight, loopFlag, activity, lower, upper, description, time, calories, intensity);
break;
}
case 4:
{
int lower = 60, upper = 90;
int activity = YOGA;
string description = "doing Hatha Yoga: ";
met(weight, loopFlag, activity, lower, upper, description, time, calories, intensity);
break;
}
case 5:
{
cout << "5 CHOSEN";
print (transactionLog);
break;
}
}
cout << setfill('0') << setw(5) << idNum << endl;
cout << choice << endl;
cout << time << endl;
cout << weightPoundsCopy << endl;
cout << calories << endl;
cout << intensity << endl;
outputFunction(transactionLog, idNum, choice, time, weightPoundsCopy, calories, intensity);
transactionLog.close();
}
while (repeat);
}
Here are what seem to be the most relevant functions
int userChoice (int choice, bool loopFlag)
{
do // loop to validate user's activity (choice) input
{
cin >> choice;
if (cin.fail() || choice > 6 || choice < 1)
{
cout << "\nInvalid choice. Please choose from option 1 through 6." << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else if (choice == 6)
{
exit(EXIT_SUCCESS); // exits program if user chooses to
}
else
{
loopFlag = false;
}
}
while (loopFlag); // loop will continue until input meets correct conditions and thus sets loopflag to false
return choice;
}
and
float userWeight(float weightPounds, bool loopFlag)
{
do // this do-while loop validates weight input
{
cout << "\nPlease enter your weight in pounds: " << endl;
cin >> weightPounds;
if (cin.fail() || weightPounds <= 0 || weightPounds >= 1000)
{
cout << "\nInvalid weight entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
return weightPounds;
}
and
void print(fstream &transactionLog)
{
// reset everything and go to the beginning of the file
transactionLog.clear();
transactionLog.seekg(0, std::ios::beg);
// start the streaming >>
if (enterPassword)
{
while(!transactionLog.eof())
{
cout << setw(20) << left << "UserID" << "Activity" << "Mins" << "Weight"
<< "Calories" << "Intensity" << "Time Stamp" << endl;
}
}
else
{
cout << "SECURITY BREACH" << endl;
return;
}
}
I think your code works as it been written. You has beed asked user made his choice by calling "userChoice" function and in anyway after that you has beed asked a user weight by calling "userWeight" function. Only after that you has been parsed user input in a switch case.
If you want that your program didn't asked user weight you should written somethin like that:
if (userInput < 5)
{
weight = userWeight(weight, loopFlag);
float weightPoundsCopy = weight;
weight = weight / 2.2;
}
So this is a very simple problem I'm sure, but I'm just starting out.
In the program, there is simple input validation. If inputed is entered properly, no issues.
The problem is, when testing the program with an error, like entering a zero or negative number, all the variables are blank (i.e., strings become blank and numbers become zero) in the output.
Thanks ahead of time for the help and insight.
// This menu driven program determines the time sound will take to travel through
// gas, liquid, and solid, given a distance from a user.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// constants
const double AIR_SPEED_RATE_PER_SECOND_SOUND = 1100.0, //in feet per second
WATER_SPEED_RATE_PER_SECOND_SOUND = 4900.0, // in feet per second
STEEL_SPEED_RATE_PER_SECOND_SOUND = 16400.0; // in feet per second
// Program defined variables
double Time_To_Travel = 0.0; // in seconds
string Medium;
// User defined variables
double distance_of_travel; //in feet
int menu_selection;
//Display a menu for mediums of sound conduction.
cout << "Sound travels at different speeds through air, water, and steel." << endl;
cout << "\nThis program will calculate the time it takes, in feet per second, for " \
"sound to travel a given distance." << endl;
cout << "Please select a number choice below:\n\n1. Air\n2. Water\n3. Steel " << endl;
//Get input from user.
cout << "\nEnter Selection: ";
cin >> menu_selection;
cout << "\nEnter distance in feet the sound will travel: ";
cin >> distance_of_travel;
// Input validate selection is on the menu
if (menu_selection >= 1 && menu_selection <= 3)
{
if (distance_of_travel > 0.0) // input validation distance is positive
{
switch (menu_selection) // calculate the time of travel based on user input
{
case 1: Medium = "air";
Time_To_Travel = distance_of_travel / AIR_SPEED_RATE_PER_SECOND_SOUND;
break;
case 2: Medium = "water";
Time_To_Travel = distance_of_travel / WATER_SPEED_RATE_PER_SECOND_SOUND;
break;
case 3: Medium = "steel";
Time_To_Travel = distance_of_travel / STEEL_SPEED_RATE_PER_SECOND_SOUND;
break;
}
}
else
{
cout << "\nPlease enter a distance greater than zero: ";
cin >> distance_of_travel;
}
}
else
{
cout << "\nMenu selection is not 1, 2, or 3.\n\nPlease correctly enter a number 1 through 3: ";
cin >> menu_selection;
}
// Format to four decimal places and display the time sound takes to travel given distance.
cout << fixed << showpoint << setprecision(4);
cout << "Sound would take " << Time_To_Travel << " seconds to travel given distance of " << distance_of_travel << " feet in " << Medium << "." << endl;;
return 0;
}
An if statement is a simple branch, not a loop. At the end of the if, execution continues past the end of the block.
if (menu_selection >= 1 && menu_selection <= 3)
This, when false, will skip the meat of your program and jump to your code that handles invalid input.
else
{
cout << "\nMenu selection is not 1, 2, or 3.\n\nPlease correctly enter a number 1 through 3: ";
cin >> menu_selection;
}
After you input menu_selection again, control flows to
cout << fixed << showpoint << setprecision(4);
cout << "Sound would take " << Time_To_Travel << " seconds to travel given distance of " << distance_of_travel << " feet in " << Medium << "." << endl;;
return 0;
The new input is never acted on, and the untouched values are printed. Replace the initial if with a do {...} while(condition); loop that wraps the user input. Once the input is satisfactory, you can then proceed to the core of the program.
bool is_good;
do
{
is_good = false;
cout << "\nEnter Selection: ";
cin >> menu_selection;
cout << "\nEnter distance in feet the sound will travel: ";
cin >> distance_of_travel;
if (menu_selection < 1 || menu_selection > 3 || distance_of_travel < 0)
cout << "error message here";
else
is_good = true;
} while (!is_good);
You can handle zero, negative number, or all possible inputs that are not defined in your case block by adding default block to your switch statement. Then your code will look like something like this.
switch (menu_selection) // calculate the time of travel based on user input
{
case 1: Medium = "air";
Time_To_Travel = distance_of_travel / AIR_SPEED_RATE_PER_SECOND_SOUND;
break;
case 2: Medium = "water";
Time_To_Travel = distance_of_travel / WATER_SPEED_RATE_PER_SECOND_SOUND;
break;
case 3: Medium = "steel";
Time_To_Travel = distance_of_travel / STEEL_SPEED_RATE_PER_SECOND_SOUND;
break;
default:
// handle zero, negative numbers and so on.
break;
}
Reference: http://www.tutorialspoint.com/cplusplus/cpp_switch_statement.htm
My updated code. When I run the code it keeps outputting the prices of all the packages instead of just the one I ask for.
#include <iostream>
using namespace std;
int main() {
// to keep it simple
int choice_a = 995;
int choice_b = 1995;
int choice_c = 3995;
char choice;
int message_units, x=1;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice;
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
do{
cout << "How many message units (enter 1 - 672)" << endl;
// again check this
cin >> message_units;
x++;
}
while(x<2);
if(message_units > 5){
choice_a += 100 * (message_units - 5);
}
cout << "Your total cost is " << choice_a /100 << "." <<choice_a%100 endl
if(message_units > 15){
choice_b += 50 * (message_units - 15);
}
cout <<"Yourtotalcostis"<<choice_b /100 << "." << choice_b%100<<endl;
(You missed an "i" or two, but English is difficult for a non-native speaker.)
Atotalcost = 9.95;
if(messageunits>5)
Atotalcost += 1.0 * (messageunits-5);
EDIT:
There are several ways to deal with amounts of money. One of them is to store an amount as a number of cents, then print it out with care. For example, the amount $2.34 is stored as int price = 234, then to print it out we print price/100 (which is 2), then a decimal point, then price%100 (which is 34, the '%' is the modulo operator, you can look it up). So the code will look like this:
#include <iostream>
using namespace std;
int main()
{
int messageunits;
cout << "how many message units(enter 1 - 672)" << endl;
cin >> messageunits;
int Atotalcost = 995; // cost of package a, in cents
if(messageunits > 5){
Atotalcost += 100 * (messageunits - 5);
}
cout << "Your total cost is " << Atotalcost/100 << "." << Atotalcost%100 << endl;
}
There is still much work to do, but this is a good start.
Along those lines, this example may have a few minor errors and I tried to keep it simple.
#include <iostream>
using namespace std;
int main() {
bool finished = false;
do {
// to keep it simple
double choice_a = 9.95;
double choice_b = 19.95;
double choice_c = 39.95;
char choice;
int message_units;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
// user enters how many units is wanted
cout << "How many message units (enter 1 - 999)" << endl;
// again check this (if homework requires checking input)
cin >> message_units;
// Calculating message units
if (message_units > 5) price += message_units * 1;
else price += message_units * 2; // if $2.00 normal?
// Total Price Output
cout << "Total: " << price << endl;
// Is user done?
char done;
cout << "Do you want to enter another? press enter to continue. If you are done, type something and press enter.";
cin >> done;
// check
if (done != '') {
finished = true;
}
}
while (finished = false);
Alright, that is about it. Two do while loops and the rest. There may be some slight errors while compiling, really, you should try to fix those yourself as this is pretty much the entire assignment...