In: Computer Science
Fat Percentage Calculator
Create a C++ program that allows the user to enter the number of calories and fat grams in a food. The application should display the percentage of the calories that come from fat. If the calories from fat are less than 30% of the total calories of the food, it should also display a message indicating the food is low in fat.
One gram of fat has 9 calories, so: Calories from fat = fat grams * 9
The percentage of calories from fat can be calculated as:
Percentage of calories from fat = Calories from fat / total calories
Input validation: Make sure the number of calories are not less than 0. Also, the number of calories from fat cannot be greater than the total number of calories. If that happens, display an error message indicating that either the calories or fat grams were incorrectly entered.
Use the following test data to determine if the application is calculating properly:
Calories and Fat Percentage Fat
200 calories, 8 fat grams Percentage of calories from fat: 36% 150 calories 2 fat grams Percentage of calories from fat: 12% (a low-fat food)
500 lories, 30 fat grams Percentage of calories from fat: 54%
Source Code:
Output:
Code in text format (See above images of code for indentation):
#include <iostream>
using namespace std;
/*main function*/
int main()
{
/*variables*/
int calories,fat,cfat;
double pcfat;
/*read total calories from user*/
cout<<"Enter the number of calories: ";
cin>>calories;
/*read fat grams in food from user*/
cout<<"Enter the fat grams in food: ";
cin>>fat;
/*calaulate calories from fat*/
cfat=fat*9;
/*if invalid input then show below message*/
if(calories<0 || cfat>calories)
cout<<"Either the calories or
fat grams were incorrectly entered";
else
/*calculate percentage*/
pcfat=(double)cfat/calories;
/*print percentage*/
cout<<"Percentage of calories from fat:
"<<pcfat*100<<"%";
/*if percentage below 30% then show below
message*/
if(pcfat<0.30)
cout<<"(a low-fat
food)";
return 0;
}