BYU Health Insurance with booleans

Problem

See BYU Health Insurance for original problem. This problem expands on that problem by requiring the use of a boolean variable to store the marital status AND checking for invalid input (i.e., invalid data type as opposed to invalid range).

Solution

/*
Test Case 1:
Input: single, 0 dependents
Output: 74
Actual: 74
 
Test Case 2:
Input: single, 2 dependents
Output: 273.50
Actual: 273.50
 
Test Case 3:
Input: married, 0 dependents
Output: 118.50
Actual: 118.50
 
Test Case 4:
Input: married, 2 dependents
Output: 413.50
Actual: 413.50
*/
 
#include <iostream>
#include <string>
#include <iomanip>
 
using namespace std;
 
const string YES = "Y";
 
const double SINGLE_NO_DEPENDENTS_PREMIUM = 74.00;
const double SINGLE_DEPENDENTS_PREMIUM = 273.50;
const double MARRIED_NO_DEPENDENTS_PREMIUM = 118.50;
const double MARRIED_DEPENDENTS_PREMIUM = 413.50;
 
int main()
{
	// INPUTS: whether single or married, dependents or no dependents
	// OUTPUT: premium
 
	cout << fixed << setprecision(2);
 
	string single_status = YES;
	int dependents_count = 0;
 
	// Prompt user
	cout << "Are you single? (Y/N) ";
	cin >> single_status;
 
	// Define boolean based on the user input
	bool is_single = (single_status == YES);
 
	cout << "How many dependents do you have? ";
	cin >> dependents_count;
 
	if (cin.fail()) // tried to read an integer, but found something else => FAILURE!
	{
		cout << "Hey, give me an integer! ";
		string dummy_input; // variable used to later consume the bad input
		cin.clear(); // we mark the cin failure as now being resolved - THIS DOES NOT CLEAR WHAT IS IN cin
		cin >> dummy_input; // consume the bad input
		cin >> dependents_count; // get the new input
	}
 
	double premium = 0.0;
 
	// Decide which premium they should pay
	if (is_single)
	{
		if (dependents_count > 0)
		{
			premium = SINGLE_DEPENDENTS_PREMIUM;
		}
		else
		{
			premium = SINGLE_NO_DEPENDENTS_PREMIUM;
		}
	}
	else
	{
		if (dependents_count > 0)
		{
			premium = MARRIED_DEPENDENTS_PREMIUM;
		}
		else
		{
			premium = MARRIED_NO_DEPENDENTS_PREMIUM;
		}
	}
 
	cout << "Given that you are " << (is_single ? "not " : "") << "married and have "
		<< dependents_count << " dependents, your premium is $" << premium << endl;
 
	system("pause");
}
cs-142/byu-health-insurance-with-booleans.txt · Last modified: 2015/05/12 19:17 by cs142ta
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0