ask how many expenses they have for the month. Loop (using a for-loop) for each of these expenses, asking how much they spent on each one. Numbering for expenses should display for the user starting at one. Keep a running track of how much they're spending as you're looping.
For each expense, verify that the expense costs at least $0.01 in a loop (using a while-loop).
They shouldn't be able to move on until they've entered in a valid expense.
Here is the code shown below. when I input 0 just to see if the while loop works, it doesn't work. Any suggestions?
int main()
{
// Variables //
double monthlyIncome, monthlySave, monthlyBudget, ex_cost = 0.01, ex_num;
int expenseMonth;
// A warm welcome message//
cout << "Welcome to the budget calculator" << endl;
// user puts in monthly income and how much they would like to save//
cout << "Please enter your starting monthly income: ";
cin >> monthlyIncome;
cout << "Please enter how much you would like to save: ";
cin >> monthlySave;
//Calculating and outputting monthly budget//
monthlyBudget = monthlyIncome - monthlySave;
cout << "Your monthly budget is: $" << monthlyBudget << endl;
// user inputs expense number //
cout << "How many expenses did you have this month: ";
cin >> expenseMonth;
// loop for expenses //
for (int i = 1; i <= expenseMonth; ++i) {
cout << "How much did you spend on expense " << i << ":" <<endl;
cin >> ex_num;
while (ex_num <= 0.01) {
cout << "you must have spent at least 0.01 for it to be an expense!" << "Please try again" << endl;
}
}
Your while loop is checking the same expense value over and over without giving the user a chance to change the value if it is not valid, thus it gets stuck in an endless loop.
Also, you are not allowing expenses to be at least 0.01 like the instructions ask for.
Try this instead:
for (int i = 1; i <= expenseMonth; ++i) {
cout << "How much did you spend on expense " << i << ":" <<endl;
cin >> ex_num;
while (ex_num < 0.01) { // <-- needs to be < not <= !
cout << "you must have spent at least 0.01 for it to be an expense! Please try again" << endl;
cin >> ex_num; // <-- add this!
}
}
Personally, I would use a do..while loop instead, since the input has to be read in at least 1 time, eg:
for (int i = 1; i <= expenseMonth; ++i) {
do {
cout << "How much did you spend on expense " << i << ":" <<endl;
cin >> ex_num;
if (ex_num >= 0.01) break;
cout << "you must have spent at least 0.01 for it to be an expense! Please try again" << endl;
}
while (true);
}
Related
When it runs the winnings or losses are taken or added from the bank and then it is run again the bank is set back to a 25$ bank not the updated bank
int main()
{
srand(time(0));
int bank = 25;
int total;
char answer;
cout << "Come play Spin the Wheel. The wheel has numbers from 1-10." << endl
<< "If you spin an even number you lose that amount. If you spin" << endl
<< "an odd number you win that amount. You start with a 25$ bank." << endl;
cout << "Your bank is $" << bank << ". Would you like to spin the wheel? (y/n):" << endl;
cin >> answer;
while (toupper(answer) == 'Y')
{
int num = rand() % 10 + 1;
if (bank <= 10)
{
cout << "Sorry you must have more than 10$ to play" << endl;
}
else if (num % 2 == 0 )
{
total = bank + num;
cout << "You spun a " << num << " and won $" << num << endl;
cout << "Your bank is now: $" << total << endl;
}
else
{
total = bank - num;
cout << "You spun a " << num << " and lost $" << num << endl;
cout << "Your bank is now: $" << total << endl;
}
cout << "Would you like to play Again (y/n) ?" << endl;
cin >> answer;
}
return 0;
}
When it runs the winnings or losses are taken or added from the bank and then it is run again the bank is set back to a 25$ bank not the updated bank
You initialize bank to be 25 dollar in this function. Inside the while loop only total is updated not bank.
Another problem arises when there is too few money to play. I suppose you would like to display your message one time, but you are stuck inside the loop because it is never broken out of.
I believe your else if and else statements are backwards.
num % 2 == 0
Would signify that the number was even, if true. The instructions say that you lose the money if the number is even.
Bank will never be less than or equal to 10 because you are never setting bank to anything after the initial 25. Its always 25.
The variable total seems redundant. Maybe add or subtract the amount rolled directly from bank.
You need to set
bank = total
else you never change its value
So I am a bit rusty in my programming skills and don't have any real world experience except for the college classes I have taken in the past. I am working on a program for a class but running into a snag;I cannot figure out how to use the value of a variable inside a For loop outside of the loop. Here is the code I am referencing:
#include "iostream"
using namespace std;
int want, have, need;
int counter = 0;
char response, cont;
int diff(int want, int have);
int main(){
cout << "Welcome!\n";
cout << "This program will help you reach your money saving goals!\n";
cout << "Would you like to use this program? (y/n)\n";
cin >> response;
while (response == 'y'){
cout << "Please enter all amounts in whole dollars only!\n";
cout << "Please enter the amount of money you would like to have saved: $";
cin >> want;
cout << "\nPlease enter the amount of money you currently have saved: $";
cin >> have;
if (have >= want){
cout << "You have already reached or exceeded your goal, this program will not be able to help you!\n";
system("Pause");
return 0;
}
cout << "\nYou need to save $" << diff(want, have) << " more money to reach your goal!\n";
cout << "Would you like me to help you with a savings plan?";
cin >> cont;
while (cont == 'y'){
int menu;
cout << "Please select from the following options: \n";
cout << "1 - Daily Saving Plan\n";
cout << "2 - Weekly Saving Plan\n";
cout << "3 - Monthly Saving Plan\n";
cout << "Enter the number associated with your choice: \n";
cin >> menu;
switch (menu){
case 1: {
int daily;
cout << "You have chosen the Daily Savings Plan\n";
cout << "How much money can you save every day? $";
cin >> daily;
for (int x = daily; x < need; x++){
daily = daily + daily;
counter++;
}
cout << "\nIt will take you " << counter << " days to reach your goal!\n";
break;
}
case 2: {
int weekly;
cout << "You have chosen the Weekly Savings Plan\n";
cout << "How much money can you save every week? $";
cin >> weekly;
for (int x = weekly; x < need; x++){
counter++;
}
cout << "\nIt will take you " << counter << " weeks to meet your goal!\n";
break;
}
case 3: {
int monthly;
cout << "You have chosen the Monthly Savings Plan\n";
cout << "How much money can you save every month? $";
cin >> monthly;
for (int x = monthly; x < need; x++){
monthly = monthly + monthly;
counter++;
}
cout << "\nIt will take you " << counter << " months to reach your goal!\n";
break;
}
default: cout << "You made an invalid selection";
cout << "Would you like to look at a different saving plan? (y/n)\n";
cin >> cont;
}
}
}
}
int diff(int want, int have){
return want - have;
}
So, when I run the program, everything runs ok, but the value of counter is always shown as "0" in the final cout statement.
I understand why it is doing this, I think..and it's because of the "int counter = 0" declaration outside the loop, so I assume it goes back to that value after the loop exits.
If I do not initiate the counter variable, I get an error, and if I declare the value inside the loop, I get an error trying to use it in the cout statement as I have above.
I'm not even sure my for loop is structured correctly...basically I want it to add to itself the weekly variable, until the total of x = need. I also want to capture how many iterations it takes for that, then output it as the number of weeks. Hopefully that all makes sense; any and all help is appreciated.
It seems like what you want to do can be done with ceil(double(need/weekly)) and that rounds up need divided by weekly.
Your declaration outside the loop doesn't affect the value you cout after you finished the for loop.
As for your problem, it looks like you never initialized need so your for loops never made an iteration as undefined is not less than or equal to 0.
A sketch in C++11 of your program.
char prompt( std::initializer_list<const char*> message, std::initializer_list<const char*> question, std::initializer_list<char> options ) {
for( auto msg:message )
std::cout << msg;
while(true) {
char response;
for( auto q:question)
std::cout << q;
std::cin >> response;
for (char option:options) {
if (response == option)
return response;
}
}
}
int prompt( std::initializer_list<const char*> message, std::initializer_list<const char*> question, int min = 0, int max = std::numeric_limits<int>::max() ) {
for( auto msg:message )
std::cout << msg;
while(true) {
int response;
for( auto q:question)
std::cout << q;
std::cin >> response;
if (response >= min && response <= max)
return response;
}
}
}
void saving( const char* plan, const char* unit, const char* units, int target ) {
int daily = prompt(
{"You have chosen the ", plan, "\n"},
{"How much money can you save every ", unit, "? $"},
1 // min saving of 1$ per unit time to prevent infinite loops
);
std::cout << "\n";
int counter = 0;
int amount_saved = 0;
while (amount_saved < target) {
++counter;
amount_saved += daily;
}
if (counter != 1)
std::cout << "It will take you " << counter << " " << units << " to reach your goal\n";
else
std::cout << "It will take you " << counter << " " << unit << " to reach your goal\n";
}
int main() {
while(
prompt(
{"Welcome!\nThis program will help you reach your money saving goals!\n"},
{"Would you like to use this program? (y/n)\n"},
{'y', 'n'}
) == 'y'
)
{
int want = prompt( {"Please enter all amounts in whole dollars only!\n"},
{"Please enter the amount of money you would like to have saved?"} );
int have = prompt( {"\n"}, {"Please enter the amount of money you currently have saved?\n"} );
std::cout << "\n";
if (have >= want) {
std::cout << "You win!\n";
system("Pause"); // ick
return 0;
}
std::cout << "You need to save $" << (have-want) << " more money to reach your goal!\n";
while( 'y' == prompt(
{},
{"Would you like me to help you with a savings plan? (y/n)"},
{ 'y', 'n' }
)) {
char menu = prompt(
{
"Please select from the following options: \n",
"1 - Daily Saving Plan\n",
"2 - Weekly Saving Plan\n",
"3 - Monthly Saving Plan\n"
},
{"Enter the number associated with your choice: \n"},
{ '1', '2', '3' }
);
switch (menu) {
case '1': {
saving( "Daily Saving Plan", "day", "days", have-want);
} break;
case '2: {
saving( "Weekly Saving Plan", "week", "weeks", have-want);
} break;
case '3': {
saving( "Monthly Saving Plan", "month", "months", have-want);
} break;
}
}
}
}
I'm not sure how to loop or repeat a cin >> cashTendered if the amount tendered is less than the required amount.
So far, this is what I have.
if (cashTendered > || == total)
{
cout << "Your change is: $" << fixed << setprecision(2) << change << ".\n\n"
<< "Have a great day!\n\n\n\n\n";
}
else
{
cout << "You did not tender enough money to cover the total cost.\n"
<< "Please enter amount of cash tendered: $";
}
So now I want the if statement to repeat until true.
any suggestions?
Have a look at loops in c++. Also if condition can be shortened to >= instead of > || ==. Moreover, since you want to repeat until the cashTendered is >= total, you need a loop that checks the condition if cashTendered is < total.
while (cashTendered < total)
{
cout << "You did not tender enough money to cover the total cost.\n"
<< "Please enter amount of cash tendered: $";
cin >> cashTendered;
}
cout << "Your change is: $" << fixed << setprecision(2) << change << ".\n\n"
<< "Have a great day!\n\n\n\n\n";
while(true)
{
cin >> cashTendered
if (cashTendered >= total)
{
cout << "Your change is: $" << fixed << setprecision(2) << change << ".\n\n"
<< "Have a great day!\n\n\n\n\n";
break;
}
else
{
cout << "You did not tender enough money to cover the total cost.\n"
<< "Please enter amount of cash tendered: $";
}
}
I had to write a program to calculate average speed of a car during a trip and I have to prompt the user for the names of the two cities that they were traveling between. That program worked, but the next program we had to write is an addition to the last one, in which the user is prompted for how many times the program should run. I declared a new variable for the number of times the users needs the program to run. However when the program enters the loop it skips the first getline() method (asking for the origin city) and skips directly to the second getline() (method asking for the destination city). I have tried clearing the buffer and declaring the loop differently, but whatever I do the string is still read into the program as an empty string. Just wondering if I made a mistake on something or if I cannot use getline() in this instance.
Using C++ and Codeblocks IDE with the GNU Compiler (I've tried other compilers too)
Anyhow here is the code.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declare Variables
string orgcity = "";
string destcity = "";
int hours = 0;
double minutes = 0.0;
int hoursmin = 0;
int minutesmin = 0;
int minutesmax = 60;
double dist = 0.0;
double totalhours = 0.0;
double avespeed = 0.0;
double num1 = 0;
cout << "How many times would you like to calculate the average speed: ";
cin >> num1;
for(num1; num1 > 0; --num1)
{
//Collect Data
cout << "Enter the city of origin: ";
getline(cin, orgcity);
cout << "Enter the destination city: ";
getline(cin, destcity);
//If Statements and Loops...Start here
do {
cout << "Enter the number of hours spent in travel: ";
cin >> hours;
if (hours < hoursmin)
cout << " Invalid number of hours - must be >= 0" << endl;
} while (hours < hoursmin);
do {
cout << "Enter the number of minutes spent in travel: ";
cin >> minutes;
if (minutes >= minutesmax){
cout <<" Invalid number of minutes - must be in range 0..59" << endl;
}
if (minutes <= minutesmin) {
cout << " Invalid number of minutes - must be in range 0..59" << endl;
}
} while (minutes >= minutesmax);
//End Here
cout << "Enter the distance (in miles) between the two cities: ";
cin >> dist;
cout << endl;
//Formula and Final Prompt
totalhours = (hours + (minutes / 60.0));
avespeed = dist / totalhours;
cout << "The average speed of the vehicle traveling" << endl;
cout << "between " << orgcity << " and " << destcity << " is " << fixed << setprecision(2) << avespeed << " miles per hour." << endl;
cout << "-------------------------------------------------------------------------------" << endl;
}
return 0;
}
When you read the number of times the loop should be run, the input operator reads the number, but leaves the newline in the buffer. This means that the first call to getline reads that single newline and nothing more.
To make sure you skip anything after that number, up to and including the newline, you can use e.g.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
My assignment is use 3 functions with parameters, as follows:
function calcRegBill – accepts one integer argument for the number of minutes used. Determines and returns the total amount due.
function calcPremBill – accepts two integer arguments, for the number of day minutes and number of night minutes used. Determines and returns the total amount due.
function printBill – accepts 4 arguments: a string account number, a character service code, an integer total number of minutes used, and an amount due. Note that this is a generic print bill function, which prints either a regular or premium bill, using the following format:
Account Number: XXXX
Service Type: Regular (or Premium, depending on the character received)
Total Minutes: XXX
Amount Due: $XXX.XX
Your main function will prompt the user for the account number and service code. Based on the service code, main will ask for the correct number of minutes, then call your functions above as needed to finish the job. In addition you must :
Incorporate a loop in your program to run the bill as many times as needed. You may do this either by a sentinel controlled loop, or with a counter controlled loop.
I already built the program and tested it with everything in the main function of the program. I am just really confused about how to break it into the 3 separate functions and have it all still work. I am a total noob at C++
Here is the program so far, I started to add the functions, but I do not believe they're right.
// Cell Bill Fun
// April 14, 2013
#include <iostream>
#include <iomanip>
using namespace std;
double calcRegBill(int a);
double calcPremBill(int b, int c);
void printBill(string acctNumber, char serviceCode, int d, double e);
int main()
{
//declare variables for question 4
char serviceCode;
int acctNumber;
int minutes;
int dayMinutes;
int nightMinutes;
int charge;
int dayFee;
int nightFee;
double amtDue;
//get input
cout << "Please enter your information to calculate your cell phone bill ";
cout << "What is your account number? (please enter a 4-digit number-example 1234): ";
cin >> acctNumber;
cout << "Do you have regular or premium service? Enter r for regular service, p for Premium.: ";
cin >> serviceCode;
//format output
cout<< setprecision(2) << fixed;
//output
switch (serviceCode)
{
case 'r':{
cout << "How many minutes did you use?: ";
cin >> minutes;
if (minutes <= 50)
amtDue = 10;
else if (minutes > 50)
amtDue=10+((minutes-50)*.20);
else
cout <<"You have input an invalid service code. Please type r for regular or p for premium service." << endl;
cout <<"Cellular Account #:" << acctNumber << endl;
cout <<"Type of Service: Regular" << endl;
cout <<"Total Minutes:" << minutes << endl;
cout <<"Amount Due: $"<< amtDue << endl;}
break;
case 'R':{
cout << "How many minutes did you use?: ";
cin >> minutes;
if (minutes <= 50)
amtDue = 10;
else if (minutes > 50)
amtDue=10+((minutes-50)*.20);
else
cout <<"You have input an invalid service code. Please type r for regular or p for premium service." << endl;
cout <<"Cellular Account #:" << acctNumber << endl;
cout <<"Type of Service: Regular" << endl;
cout <<"Total Minutes:" << minutes << endl;
cout <<"Amount Due: $"<< amtDue << endl;}
break;
case 'p':
cout << "How many daytime minutes did you use?";
cin >> dayMinutes;
if (dayMinutes <= 75)
dayFee = 0;
else if (dayMinutes > 75)
dayFee=((dayMinutes-75)*.10);
cout << "How many night time minutes did you use?";
cin >> nightMinutes;
if (nightMinutes <= 100)
nightFee = 0;
else if (nightMinutes > 100)
nightFee=((nightMinutes-100)*.05);
else
cout <<"You have input an invalid service code. Please type r for regular or p for premium service." << endl;
cout <<"Cellular Account #:" << acctNumber << endl;
cout <<"Type of Service: Premium" << endl;
cout <<"Total Minutes:" <<dayMinutes+nightMinutes << endl;
cout <<"Amount Due: $"<<25<<"+"<<dayFee<<"+"<<nightFee<<"= $"<<25+dayFee+nightFee << endl;
break;
case 'P':
cout << "How many daytime minutes did you use?";
cin >> dayMinutes;
if (dayMinutes <= 75)
dayFee = 0;
else if (dayMinutes > 75)
dayFee=((dayMinutes-75)*.10);
cout << "How many night time minutes did you use?";
cin >> nightMinutes;
if (nightMinutes <= 100)
nightFee = 0;
else if (nightMinutes > 100)
nightFee=((nightMinutes-100)*.05);
else
cout <<"You have input an invalid service code. Please type r for regular or p for premium service." << endl;
cout <<"Cellular Account #:" << acctNumber << endl;
cout <<"Type of Service: Premium" << endl;
cout <<"Total Minutes:" <<dayMinutes+nightMinutes << endl;
cout <<"Amount Due: $"<<25<<"+"<<dayFee<<"+"<<nightFee<<"= $"<<25+dayFee+nightFee << endl;
break;
default:
cout << "Invalid Service Code. Enter r for regular service, p for Premium.";
}
return 0;
}
double calcRegBill(int a)
{
}
double calcPremBill(int b, int c)
{
}
void printBill(string acctNumber, char serviceCode, int d, double e )
{
return;
}
Functions work by requesting data (the parameters you pass to them), and operating on this data, often by returning data.
For example, in the case 'r': block, instead of of your code, you would want to have:
cout << "How many minutes did you use?: ";
cin >> minutes;
amtDue = calcRegBill(minutes);
cout <<"Cellular Account #:" << acctNumber << endl;
cout <<"Type of Service: Regular" << endl;
cout <<"Total Minutes:" << minutes << endl;
cout <<"Amount Due: $"<< amtDue << endl;}
break;
Then, you can move the code that was previously in main to calculate amtDue into the calcRegBill() function, like this:
double calcRegBill(int minutes)
{
double bill;
if (a < 50)
bill = 10;
else
bill = 10+((minutes-50)*.20);
return bill;
}
The key here is that instead of calculating amtDue in the main function, you calculate it in the calcRegBill function and return it to the main function. Also, notice that I changed the name of the parameter from a to minutes. This improves clarity of its purpose in the function.
The general structure of your program is mostly correct, and I am not really sure what you are asking.
For trouble shooting, write one of your functions and test it without all the other stuff. For example, write calcRegBill...
Then write a very simple main:
int main() {
cout << calcRegBill(3) << endl;
cout << calcRegBill(11) << endl;
}
Did you get the values expected? If so then move on to the next function. Development is often about breaking the problem down into smaller manageable problems.
You need to break down the flow of what you're doing.
First, you gather information. Note: The information you're looking for is the same, regardless of whether it's a premium or regular bill. You don't need to branch so early.
In order to calculate their bill, you branch based on premium or regular. Either way, you get back a double from this, so you can have a double variable that you store the return from calcRegBill or calcPremBill into. Declare this double variable before the branch, assign to it inside of your two branches (regular or premium).
Then, when you call printBill, you can pass this value and what type of bill it was.