# how to calculate correctly? the formula or output seems incorrect for my coding

+12 votes
asked Jul 23, 2023
#include <iostream>

#include <iomanip>

using namespace std;

float calculatePrice(char menu,int dish);

float memberDiscount (char answer);

void display_total (int totalAllquantity,float price,float totalPrice,float overAllPrice,float sumTotal);

int main()

{

char answer, menu, member;

float price, totalPrice,sumTotal=0,overAllPrice,AmountDiscount,discount;

int dish,totalAllQuantity=0;

cout << "*** Welcome to irenic cafe ^^ ***";

cout << "\nDo you want to start an order? (y/n): ";

cin >> answer;

// menu display

while (answer!='n')

{

cout<<" \nJ: Japanese cuisine, C: Chinese cuisine , K: Korean cuisine";

cout<<"\n**************************************************************************";

cout << "\nPlease take a look at our menu (J/C/K): ";

cin >> menu;

if (menu == 'J')

{

cout << "\nJapanese cuisine";

cout << "\n1. Ebi tempura udon\n2. Japanese curry with rice\n3. Sukiyaki\n";

}

else if (menu == 'C')

{

cout << "\nChinese cuisine";

cout << "\n1. Chicken dumplings\n2. Chinese Fried rice\n3. Mee Tarik with sliced beef\n";

}

else if (menu == 'K')

{

cout << "\nKorean cuisine";

cout << "\n1. Rose tteokbokki\n2. Cheese Ramyeon\n3. Rabokki\n";

}

else

{

cout << "\nInvalid choice. Please select a valid cuisine from the menu (J/C/K)." << endl;

}

// customer's chosen menu

cout<<"\nThe dishes are selected depending on the numbers (1/2/3)^^";

cout << "\nEnter your selected dish (1/2/3): ";

cin >> dish;

cout << "Enter the quantity: ";

cin >> totalAllQuantity;

//member discount

cout<<"Are you a member? (y/n): ";

cin>>member;

//function call

totalPrice=calculatePrice(menu,dish);

AmountDiscount=memberDiscount(answer);

overAllPrice=totalPrice-AmountDiscount;

totalAllQuantity++;

sumTotal=sumTotal+overAllPrice;

cout << "Do you want to add more order? (y/n): ";

cin >> answer;

}

display_total (totalAllQuantity,price,totalPrice,overAllPrice,sumTotal);

return 0;

}

//function definition

//function type , function name (formal parameter list)

float calculatePrice(char menu,int dish)

{

float price;

if (menu == 'J' && dish == 1)

price = 15.00;

else if (menu == 'J' && dish == 2)

price = 20.00;

else if (menu == 'J' && dish == 3)

price = 18.00;

else if (menu == 'C' && dish == 1)

price = 12.00;

else if (menu == 'C' && dish == 2)

price = 8.00;

else if (menu == 'C' && dish == 3)

price = 15.80;

else if (menu == 'K' && dish == 1)

price = 15.00;

else if (menu == 'K' && dish == 2)

price = 10.00;

else if (menu == 'K' && dish == 3)

price = 17.00;

return price;

}

//function definition

//function type , function name (formal parameter list)

float memberDiscount (char answer)

{

float discount;

if (answer=='y')

discount=0.20;

else

discount=0.00;

return discount;

}

//function definition

//function type  function name (formal parameter list)

void display_total (int totalAllQuantity,float price,float totalPrice,float overAllPrice,float sumTotal)

{      // order summary

cout << "\nYour order summary:" << endl;

cout << "-------------------" << endl;

cout << "Quantity: " << totalAllQuantity << endl;

cout << "Price per item: RM " <<fixed<<setprecision (2)<< price << endl;

cout << "Total price: RM " <<fixed<<setprecision (2)<< totalPrice << endl;

cout<<"Total price after member discount:RM "<<fixed<<setprecision (2)<<overAllPrice << endl;

cout<<"Your overall total is:RM  "<<fixed<<setprecision (2)<<sumTotal<<endl;

cout << "\nYour order has been placed." << endl;

}

## 4 Answers

0 votes
answered Jul 24, 2023 by (88,520 points)
edited Jul 24, 2023 by Peter Minarik

# Problems in your code

I've added // TODO: comments to your code to highlight issues I've identified with it. See it below:

```#include <iostream>
#include <iomanip>

using namespace std;

float calculatePrice(char menu,int dish);
float memberDiscount (char answer);
void display_total (int totalAllquantity,float price,float totalPrice,float overAllPrice,float sumTotal);

int main()
{
char answer, menu, member;
float price, totalPrice, sumTotal = 0, overAllPrice, AmountDiscount, discount;
int dish, totalAllQuantity = 0;
cout << "*** Welcome to irenic cafe ^^ ***";
cout << "\nDo you want to start an order? (y/n): ";
cin >> answer;
// menu display
while (answer !='n')
{
cout << "\nJ: Japanese cuisine, C: Chinese cuisine , K: Korean cuisine";
cout << "\n**************************************************************************";
cout << "\nPlease take a look at our menu (J/C/K): ";
cin >> menu;
// TODO: User experience would improve a lot if case insensitivity would be introduce. E.g. you turn menu to upper case after the input. Look at toupper() in the header <cctype>
if (menu == 'J')
{
cout << "\nJapanese cuisine";
cout << "\n1. Ebi tempura udon\n2. Japanese curry with rice\n3. Sukiyaki\n";
}
else if (menu == 'C')
{
cout << "\nChinese cuisine";
cout << "\n1. Chicken dumplings\n2. Chinese Fried rice\n3. Mee Tarik with sliced beef\n";
}
else if (menu == 'K')
{
cout << "\nKorean cuisine";
cout << "\n1. Rose tteokbokki\n2. Cheese Ramyeon\n3. Rabokki\n";
}
else
{
cout << "\nInvalid choice. Please select a valid cuisine from the menu (J/C/K)." << endl;
// TODO: You should go back and repeatedly ask the user to get the right J/C/K input and not continue with the dish.
}

// customer's chosen menu
cout << "\nThe dishes are selected depending on the numbers (1/2/3)^^";
cout << "\nEnter your selected dish (1/2/3): ";
cin >> dish; // TODO: No erro handling here if the entered data is not 1/2/3?
cout << "Enter the quantity: ";
cin >> totalAllQuantity;

//member discount
cout << "Are you a member? (y/n): ";
cin >> member;

//function call
totalPrice = calculatePrice(menu, dish); // TODO: I wouldn't call this `totalPrice` but `dishPrice` or similar to avoid confusion what is stored in this variable.
AmountDiscount = memberDiscount(answer);
overAllPrice = totalPrice - AmountDiscount;

totalAllQuantity++; // TODO: Why do you increment totalAllQuantity? This variable ment how many the client have ordered from the given dish.
sumTotal = sumTotal + overAllPrice;

cout << "Do you want to add more order? (y/n): ";
cin >> answer;
}

// TODO: the value of `price` is never set
// TOOD: I don't see where the dish price is multiplied by how many dishes are ordered.
display_total(totalAllQuantity, price, totalPrice, overAllPrice, sumTotal);
return 0;
}

//function definition
//function type , function name (formal parameter list)
float calculatePrice(char menu, int dish)
{
float price;
if (menu == 'J' && dish == 1)
price = 15.00;
else if (menu == 'J' && dish == 2)
price = 20.00;
else if (menu == 'J' && dish == 3)
price = 18.00;
else if (menu == 'C' && dish == 1)
price = 12.00;
else if (menu == 'C' && dish == 2)
price = 8.00;
else if (menu == 'C' && dish == 3)
price = 15.80;
else if (menu == 'K' && dish == 1)
price = 15.00;
else if (menu == 'K' && dish == 2)
price = 10.00;
else if (menu == 'K' && dish == 3)
price = 17.00;

return price;
}

//function definition
//function type , function name (formal parameter list)
float memberDiscount(char answer)
{
float discount;
if (answer == 'y')
discount = 0.20;
else
discount = 0.00;

return discount;
}

//function definition
//function type  function name (formal parameter list)
void display_total(int totalAllQuantity, float price, float totalPrice, float overAllPrice, float sumTotal)
{
// order summary
cout << "\nYour order summary:" << endl;
cout << "-------------------" << endl;
cout << "Quantity: " << totalAllQuantity << endl;
cout << "Price per item: RM " << fixed << setprecision (2) << price << endl; // TODO: 2 digits is not enough to display the number.
cout << "Total price: RM " << fixed << setprecision (2) << totalPrice << endl; // TODO: 2 digits is not enough to display the number.
cout << "Total price after member discount:RM "<< fixed << setprecision (2) << overAllPrice << endl;
cout<<"Your overall total is:RM  "<< fixed << setprecision (2) << sumTotal << endl; // TODO: 2 digits is not enough to display the number.
cout << "\nYour order has been placed." << endl;
}
```
commented Jul 25, 2023 by (230 points)
thank you so much for helping me i really appreciate it sir
+1 vote
answered Jul 24, 2023 by (88,520 points)
edited Jul 25, 2023 by Peter Minarik

# A better solution

I think a better solution would be to collect all the items in the orders in a list (std::vector) so they can be accessed during the final display.

See my attempt below.

```#include <cstring>
#include <iostream>
#include <limits>
#include <string>
#include <vector>

const float discount = 0.1f;

struct MenuItem
{
std::string name;
float price;
};

struct OrderEntry
{
MenuItem menuItem;
unsigned int quantity;
};

struct Order
{
std::vector<OrderEntry> items;
bool hasDiscount;
} order;

MenuItem japaneseMenu[] =
{
{ "Ebi tempura udon", 15.0f },
{ "Japanese curry with rice", 20.0f },
{ "Sukiyaki", 18.0f }
};

MenuItem chineseMenu[] =
{
{ "Chicken dumplings", 12.0f },
{ "Chinese Fried rice", 8.0f },
{ "Mee Tarik with sliced beef", 15.8f }
};

MenuItem koreanMenu[] =
{
{ "Rose tteokbokki", 15.0f },
{ "Cheese Ramyeon", 10.0f },
{ "Rabokki", 17.0f }
};

char GetValidChoice(const char * validChoices)
{
char answer;
do
{
std::cin >> answer;
answer = std::toupper(answer);
}
while (std::strchr(validChoices, answer) == nullptr);

return answer;
}

unsigned int GetUint()
{
unsigned int number;
bool success = false;
do
{
std::cin >> number;
if (std::cin) // user entered a valid number
{
success = true;
}
else // user didn't input a number
{
std::cin.clear(); // reset failbit
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
}
} while (!success);
return number;
}

OrderEntry OrderFromMenu(MenuItem menu[], unsigned int menuSize)
{
// Note: this simple logic works only up to 9 items in the list.
char validChoices[10] { '\0' };
for (unsigned int i = 0; i < menuSize; i++)
{
std::cout << i + 1 << ". " << menu[i].name << " (\$" << menu[i].price << ")" << std::endl;
validChoices[i] = '1' + i;
}

std::cout << "The dishes are selected depending on the numbers (1/2/3)^^" << std::endl;
std::cout << "Enter your selected dish (1/2/3): " << std::endl;
unsigned int itemId = GetValidChoice(validChoices) - '1';
OrderEntry orderEntry;
orderEntry.menuItem = menu[itemId];

std::cout << "Please, enter the quantity: ";
orderEntry.quantity = GetUint();
return orderEntry;
}

void DisplayOrder()
{
float total = 0;
printf("\n               ORDER SUMMARY\n");
printf("===========================================\n");
for (OrderEntry orderEntry : order.items)
{
printf("%-30s \$%7.2f x %u\n", orderEntry.menuItem.name.c_str(), orderEntry.menuItem.price, orderEntry.quantity);
total += orderEntry.menuItem.price * orderEntry.quantity;
}

printf("-------------------------------------------\n");
if (order.hasDiscount)
{
printf("%-30s \$%7.2f\n", "Total before discount", total);
printf("*** %d%% DISCOUNT APPLIED ***\n", (int)(discount * 100));
total *= (1.0f - discount);
}
else
{
printf("*** NO DISCOUNT ***\n");
}

printf("-------------------------------------------\n");
printf("%-30s \$%7.2f\n", "GRAND TOTAL", total);
}

int main()
{
std::cout << "*** Welcome to irenic cafe ^^ ***" << std::endl;
std::cout << "Would you like to start an order? (y/n): ";
while (GetValidChoice("YN") != 'N')
{
std::cout << std::endl << "J: Japanese cuisine, C: Chinese cuisine, K: Korean cuisine" << std::endl;
std::cout << "**************************************************************************" << std::endl;
std::cout << "Please take a look at our menu (J/C/K): ";
switch (GetValidChoice("JCK"))
{
case 'J': order.items.push_back(OrderFromMenu(japaneseMenu, sizeof(japaneseMenu) / sizeof(MenuItem))); break;
case 'C': order.items.push_back(OrderFromMenu(chineseMenu, sizeof(chineseMenu) / sizeof(MenuItem))); break;
case 'K': order.items.push_back(OrderFromMenu(koreanMenu, sizeof(koreanMenu) / sizeof(MenuItem))); break;
}

std::cout << "Would you like to add more to your order? (y/n): ";
}

if (order.items.size() == 0)
return 0;

std::cout << "Are you a member? (y/n): ";
order.hasDiscount = GetValidChoice("YN") == 'Y';
DisplayOrder();
return 0;
}```

Note: I used printf() in DisplayOrder() as formatting with std::cout can be quite cumbersome.

0 votes
answered Jul 24, 2023 by (1,580 points)

Hello, this is Gulshan Negi
Well, I searched about it on Google and found some problems with your commands.
Here is the correct code that you can try for what you are looking for.

int main()
{
char answer, menu, member;
float price, totalPrice, sumTotal = 0, overAllPrice, AmountDiscount, discount;
int dish, totalAllQuantity = 0;

cout << "*** Welcome to irenic cafe ^^ ***";

cout << "\nDo you want to start an order? (y/n): ";
cin >> answer;

while (answer != 'n')
{
// ... (existing code)

// customer's chosen menu
cout << "\nThe dishes are selected depending on the numbers (1/2/3)^^";
cout << "\nEnter your selected dish (1/2/3): ";
cin >> dish;
cout << "Enter the quantity: ";
cin >> totalAllQuantity;

// member discount
cout << "Are you a member? (y/n): ";
cin >> member;

// function call
totalPrice = calculatePrice(menu, dish);
AmountDiscount = memberDiscount(member);

overAllPrice = totalPrice - AmountDiscount;

sumTotal += (totalAllQuantity * overAllPrice); // Fix the calculation here

cout << "Do you want to add more order? (y/n): ";
cin >> answer;
}

display_total(totalAllQuantity, price, totalPrice, overAllPrice, sumTotal);

return 0;
}

I hope you will right result.
Thanks

commented Jul 25, 2023 by (230 points)
thank you so much for helping me , i really appreciate it!
0 votes
answered Aug 25, 2023 by (220 points)

Your C++ code appears to be a simple program for taking food orders from a menu, calculating prices, applying member discounts, and displaying an order summary. The code structure looks fine, and it seems to achieve the intended functionality. However, I noticed a couple of things you might want to consider:

1. Member Discounts: It looks like you're applying a flat discount of 20% if the customer is a member. You might want to check if this is the desired behavior, as typically, discounts are applied to the individual items rather than the total order.

2. Quantity Handling: You're using totalAllQuantity to keep track of the quantity of items ordered. However, you might want to keep track of the quantity of each item separately so that you can calculate the total price for each item and then sum them up for the order total.

3. Price Calculation: Currently, you're using a fixed price for each menu item. It's common to have a more dynamic pricing structure, where the prices are read from a data source (like a file or database) to allow for easy changes in pricing without modifying the code.

4. Indentation and Formatting: While the code is functional, it's a good practice to follow consistent code formatting and indentation to make the code more readable and maintainable.

5. Input Validation: You might want to consider adding input validation to ensure that the user enters valid choices, quantities, and responses.

6. Handling Currency Values: When dealing with currency values, it's often better to use integer types (like int or long) to represent amounts in cents to avoid floating-point precision issues.

Here is corrected code:

#include <iostream>
#include <iomanip>

using namespace std;

struct MenuItem {
string name;
float price;
};

MenuItem menuItems[] = {
{"Ebi tempura udon", 15.00},
{"Japanese curry with rice", 20.00},
{"Sukiyaki", 18.00},
{"Chicken dumplings", 12.00},
{"Chinese Fried rice", 8.00},
{"Mee Tarik with sliced beef", 15.80},
{"Rose tteokbokki", 15.00},
{"Cheese Ramyeon", 10.00},
{"Rabokki", 17.00}
};

float calculatePrice(int itemIndex, int quantity) {
if (itemIndex >= 0 && itemIndex < sizeof(menuItems) / sizeof(menuItems[0])) {
return menuItems[itemIndex].price * quantity;
}
return 0.0;
}

float applyMemberDiscount(float totalPrice, char answer) {
if (answer == 'y' || answer == 'Y') {
return totalPrice * 0.8; // 20% discount for members
}
return totalPrice;
}

int main() {
char answer, menu, member;
float totalPrice, sumTotal = 0.0;
int itemIndex, quantity;

cout << "*** Welcome to irenic cafe ^^ ***";

do {
cout << "\nDo you want to start an order? (y/n): ";
cin >> answer;

if (answer == 'n' || answer == 'N') {
break;
}

cout << "\nJ: Japanese cuisine, C: Chinese cuisine, K: Korean cuisine";
cout << "\nPlease take a look at our menu (J/C/K): ";
cin >> menu;

if (menu == 'J' || menu == 'C' || menu == 'K') {
cout << "\nYour selected dish: " << menuItems[itemIndex].name << endl;
cout << "Enter the quantity: ";
cin >> quantity;
} else {
cout << "\nInvalid choice. Please select a valid cuisine from the menu (J/C/K)." << endl;
continue;
}

cout << "Are you a member? (y/n): ";
cin >> member;

totalPrice = calculatePrice(itemIndex, quantity);
totalPrice = applyMemberDiscount(totalPrice, member);

sumTotal += totalPrice;

cout << "Do you want to add more order? (y/n): ";
cin >> answer;
} while (answer != 'n' && answer != 'N');

cout << "\nYour order summary:" << endl;
cout << "-------------------" << endl;
cout << "Total price: RM " << fixed << setprecision(2) << sumTotal << endl;
cout << "Thank you for ordering with us!" << endl;

return 0;
}