24.6k views
2 votes
Write a program in C++ that calculates and displays a food’s fat calories and fat percentage. Have the user enter the:

1) name of the food item (such as a Snickers Bar)
2) total calories of the item and
3) grams of fat for the item. Validate the data to be assured that the user didn’t enter negative calories or fat grams.
Multiply the fat grams by 9 to figure out the fat calories. To figure out fat percentage, divide the fat calories by the total calories then multiply by 100.0. Print out the results. Allow the user to keep entering food items until the word "stop" is entered.

User Iluvcapra
by
7.7k points

1 Answer

4 votes

Final answer:

Here is an example program in C++ that calculates and displays a food's fat calories and fat percentage.

It uses a while loop to keep asking the user for input until the word 'stop' is entered, validates the data entered by the user, and calculates the fat calories and fat percentage using the given formulas.

Step-by-step explanation:

Here is an example program in C++ that calculates and displays a food's fat calories and fat percentage:

#include <iostream>
#include <string>
using namespace std;

int main() {
string itemName;
int totalCalories;
int fatGrams;

cout << "Enter the name of the food item: ";
getline(cin, itemName);

cout << "Enter the total calories of the item: ";
cin >> totalCalories;

cout << "Enter the grams of fat for the item: ";
cin >> fatGrams;

while (totalCalories >= 0 && fatGrams >= 0) {
int fatCalories = fatGrams * 9;
float fatPercentage = ((float)fatCalories / totalCalories) * 100.0;

cout << "Food: " << itemName << endl;
cout << "Fat Calories: " << fatCalories << endl;
cout << "Fat Percentage: " << fatPercentage << "%" << endl;

cout << "\\Enter the name of the food item: ";
cin.ignore();
getline(cin, itemName);

cout << "Enter the total calories of the item: ";
cin >> totalCalories;

cout << "Enter the grams of fat for the item: ";
cin >> fatGrams;
}

return 0;
}

This program uses a while loop to keep asking the user for input until the word 'stop' is entered. It validates the data entered by the user to ensure that the total calories and fat grams are not negative. It then calculates the fat calories by multiplying the fat grams by 9, and the fat percentage by dividing the fat calories by the total calories and multiplying by 100.0. Finally, it prints out the results for each food item entered by the user.

User Stephanlindauer
by
8.6k points