C++ switch statement not working properly - c++

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;
}

Related

How do I get the variable to accumulate? C++

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;
}

Doing while loop properly until "0" input to stop the loop?

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!

The program crashed when executed on Visual Studio but it ran properly on cpp.sh website

guys! Down here is the code that I have for my Bank assignment. It ran well when I chose Case 1 to check the Balance. However, when I chose Case 2 for Depositing, the program crashes right after entering the amount of deposit. I looked through the code but I'm not sure where the problem came from. However, the program seems to run ok when executed on cpp.sh website and only crashes on Visual Studio. Is it because of my code or my compiler?
#include <iostream>
#include <string>
using namespace std;
class account {
private:
double AccountActivity[200];
double balance;
int numTransactions;
public:
//declaration
};
void account::test() {
account a;
int choice;
bool menu = true;
double amount = 0;
while (menu = true) {
choice = a.getUserChoice();
switch (choice) {
case 1:
a.print();
break;
case 2:
cout << "\n\nPlease enter the amount of deposit: " << endl;
cin >> amount;
a.deposit(amount);
break;
case 3:
cout << "\n\nPlease enter the amount of withdrawal: " << endl;
cin >> amount;
a.withdraw(amount);
break;
case 4:
cout << "The largest deposit is: " << a.getLargest() << endl;
default:
cout << "Please choose from 1 to 4" << endl;
break;
}
}
}
int account::getUserChoice() {
//do something
}
double account::getLargest()
{
//do something
}
void account::print() {
cout << "Your balance is: $" << balance;
cout << "\n\n";
}
account::account() {
balance = 0;
}
void account::deposit(double amount) {
if (numTransactions < 200)
{
AccountActivity[numTransactions] = amount;
numTransactions++;
balance += amount;
}
}
void account::withdraw(double amount) {
if (balance < amount)
cout << "Insufficient balance" << endl;
else
{
if (amount >= 0 && numTransactions < 200)
{
AccountActivity[numTransactions] = -amount;
numTransactions++;
balance -= amount;
}
}
}
int main() {
//do something
}
numTransactions is not initialized. Using an uninitialized value to index into an array is undefined behavior.
In your account constructor account::account() set numTransactions to 0
Oh yeah: while (menu = true) { try while(menu) - but then you don't change menu inside the loop so you might as well make it while(1) {

Need help creating an equation in C++ to calculate total

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...

How to display differences in prices using switch statements in C++

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.