The below code works fine, but I believe there is a cleaner way of coding it. I need the program to quit immediately if a negative value for age is entered. Thanks all!
#include <iostream>
bool target_heart_rate_calc(int, int); //Func prototype for target heart rate calc, which returns bool
usingnamespace std;
int main()
{
int age = 1, heart_bpm = 0; // Declare and initialize input variables
bool within_heart_rate = 1;
do
{
cout << "Enter your age, or enter a negative number to quit: ";
cin >> age;
if (age < 0) // If negative value for age is entered, program will exit
break;
else
{
cout << "Enter your heart beats per minute: ";
cin >> heart_bpm;
within_heart_rate = target_heart_rate_calc(age, heart_bpm);
if (within_heart_rate)
cout << "You are in your target heart rate. " << endl;
else
cout << "You are not in your target heart rate. " << endl;
}
} while (age > 0); // Loop will continue until a negative number for age is entered
return 0;
}
bool target_heart_rate_calc(int age, int bpm) //function body
{
bool within_target_heart_rate;
double maximal_heart_rate = 0.0, calculated_target_heart_rate = 0.0;
maximal_heart_rate = (220 - age) ;
calculated_target_heart_rate = (bpm / maximal_heart_rate) * 100;
if (calculated_target_heart_rate >= 60.0 && calculated_target_heart_rate <= 70.0)
within_target_heart_rate = true;
else
within_target_heart_rate = false;
return within_target_heart_rate;
}
Thanks for the response andy. I changed it to the following code, but arent the while loop arguments useless anyway? By that I mean the if statement is the one that actually will break up the loop, not the while loop. Thanks for your help.
while (age > 0)
{
cout << "Enter your age, or enter a negative number to quit: ";
cin >> age;
if (age < 0) // If negative value for age is entered, program will exit
break;
else
{
cout << "Enter your heart beats per minute: ";
cin >> heart_bpm;
within_heart_rate = target_heart_rate_calc(age, heart_bpm); // Call heart rate calc function and pass age and bpm to it
if (within_heart_rate) // If return value from function is true, output message to user
cout << "You are in your target heart rate. " << endl;
else // If return value from function is false, output message to user
cout << "You are not in your target heart rate. " << endl;
}
}
return 0;
}