Ok so i'm working on this project and its a travel expense program. Basically it just has some functions that gets info from the user. I'm having a problem with my for loop. The running total is messing up. The numbers end up like 2 or 4 numbers off of what there supposed to be. Here's the code(I know it's not neat or anything i will clean that up later)
#include <iostream>
#include <fstream>
using namespace std;
int getDays(int);
double getDepartureTime();
double getArrivalTime(double);
double airFees(double);
double carRentalFees(double);
double getMilesDriven(double);
double getParkingTotal(double,double);
double getParkingSpent(double,double);
double getTaxiFees(double,double);
double employeeHotelExpense(double,double);
double getHotelExpense(double,double);
double getMealExpenses(double,double);
void timeEquivalent();
double breakFastFee = 0;
int main()
{
int days=0, amount=0, departure_conference=0, departure_home=0,time = 0;
double airFee=0,taxiFeesAllowed,parkingAllowed = 0,employeeHotelExpense = 0,employeeTaxiFees = 0, milesDriven=0,
parkingFees=0, taxiFees=0, yes=0,arrivalTime = 0;
double carRentalFee = 0, hotel_expenses=0,departureTime = 0, meals=0,employeeMealExpenses = 0, parkingSpent = 0,allowableHotelExpense = 0
,allowedMealTotal = 0,mealsSpent = 0;
char employee[40];
//timeEquivalent();
//cout << "What Time Did You Arrive " <<endl;
//cin >>time;
days = getDays(days);
timeEquivalent();
departureTime = getDepartureTime();
arrivalTime = getArrivalTime(arrivalTime);
airFee = airFees(airFee);
carRentalFee = carRentalFees(carRentalFee);
milesDriven = getMilesDriven(milesDriven);
parkingAllowed = 6 * days;
parkingSpent = getParkingSpent(parkingSpent,days);
taxiFeesAllowed = days * 10;
employeeTaxiFees = getTaxiFees(taxiFees,days);
allowableHotelExpense = 90 * days;
employeeHotelExpense = getHotelExpense(employeeHotelExpense, days);
employeeMealExpenses = getMealExpenses(departureTime,arrivalTime);
cout << employeeMealExpenses <<endl;
return 0;
}
int getDays(int days)
{
cout << " How many Days did you stay on the trip " <<endl;
cin >> days;
while(days < 0)
{
cout <<"Please enter a value greater than 0 :D " <<endl;
cin >> days;
}
return days;
}
double getDepartureTime()
{
double departureTime;
cout << "Please Refer To The Menu Above and enter the time of departure in military\n";
cout << "Time. For example if you departed at 7:30 enter 0730\n\n";
cin >> departureTime;
return departureTime;
}
double getArrivalTime(double arrivalTime)
{
cout << "Please refer to the menu above and enter the time you arrived back home in\n";
cout <<" military format\n";
cin >> arrivalTime;
return arrivalTime;
}
double airFees(double airfee)
{
cout << " How Much Were Your Air Fees " <<endl;
cin >> airfee;
while(airfee < 0)
{
cout <<" Please enter a value greater than 0 :D " <<endl;
cin >> airfee;
}
return airfee;
}
double carRentalFees(double carRentalFee)
{
cout << " How Much were Your Car Rental Fees " <<endl;
cin >> carRentalFee;
while(carRentalFee < 0)
{
cout <<"Please enter a value of 0 or greater :D " <<endl;
cin >> carRentalFee;
}
return carRentalFee;
}
double getMilesDriven(double milesDriven)
{
const double mileRate = 0.27;
cout << " How many miles did you drive, please enter 0 if a private vehicle was not used " <<endl;
cin >> milesDriven;
while(milesDriven < 0)
{
cout << " Please Enter 0 or Greater:)"<<endl;
cin >> milesDriven;
}
return mileRate * milesDriven;
}
double getParkingSpent(double parkingSpent, double days)
{
cout << " How Much Did You Spend on Parking " <<endl;
cin >> parkingSpent;
while(parkingSpent < 0)
{
cout << "Please Enter an Amount of 0 or Greater "<<endl;
cin >> parkingSpent;
}
return parkingSpent*days;
}
double getTaxiFees(double taxiFees,double days)
{
cout << " Please Enter The Amount of Taxi Fees Please " <<endl;
cin >> taxiFees;
while(taxiFees < 0)
{
cout << "Please Enter an Amount of 0 or Greater "<<endl;
cin >> taxiFees;
}
return taxiFees * days;
}
double getHotelExpense(double employeeHotelExpense,double days)
{
cout << " How Much Were Your Hotel Expenses " <<endl;
cin >> employeeHotelExpense;
while(employeeHotelExpense < 0)
{
cout << "Please Enter a Amount of 0 or Greater "<<endl;
cin >> employeeHotelExpense;
}
return employeeHotelExpense * days;
}
double getMealExpenses(double departureTime,double arrivalTime)
{
static double breakFastFee = 0 ;
static double lunchFee = 0 ;
static double dinnerFee = 0 ;
int numberOfDays = 2 ;
double total = 0;
for(int days =1;days <=numberOfDays;days++)
{
if ( days < numberOfDays && departureTime > 000 && departureTime < 700)
{
cout << "Please Enter Your breakfast cost"<<endl;
cin >> breakFastFee;
cout << " Please Enter Your Lunch Cost " <<endl;
cin >>lunchFee;
cout << "Please Enter Your Dinner Cost " <<endl;
cin >> dinnerFee;
}
if (days < numberOfDays && departureTime > 700 && departureTime <=1200)
{
cout << "Please Enter Your Lunch Cost"<<endl;
cin >> lunchFee;
cout << "Please Enter Your Dinner cost "<<endl;
cin >> dinnerFee;
}
if(days < numberOfDays && departureTime > 1201 && departureTime <= 1800)
{
cout << "Enter The Cost of Dinner " <<endl;
cin >> dinnerFee;
}
if(days == numberOfDays && arrivalTime > 800 && arrivalTime<=1300)
{
cout <<"Enter The Cost of Breakfast " <<endl;
cin >> breakFastFee;
}
if(days == numberOfDays && arrivalTime > 1301 && arrivalTime <= 1900)
{
cout << "Enter The Cost of Breakfast "<<endl;
cin >> breakFastFee;
cout << " Enter The Cost of Lunch " <<endl;
cin >> lunchFee;
}
if(days == numberOfDays && arrivalTime > 1901)
{
cout << "Enter The Cost of Breakfast " <<endl;
cin >> breakFastFee;
cout << " Enter The Cost of Lunch " <<endl;
cin >> lunchFee;
cout << "Enter The Cost of Dinner " <<endl;
cin >> dinnerFee;
}
total+=breakFastFee + lunchFee + dinnerFee;
}
return total;
}
void timeEquivalent()
{
cout <<"Regular Time " << "\t\t" <<"Military Time \n";
cout <<"************" << "\t\t" <<"***************"<<endl;
cout <<"Midnight " << "\t\t" <<"0000 \n";
cout <<"1:00a.m. " << "\t\t" <<"0100 \n";
cout <<"2:00a.m. " << "\t\t" <<"0200 \n";
cout <<"3:00a.m. " << "\t\t" <<"0300 \n";
cout <<"4:00a.m. " << "\t\t" <<"0400 \n";
cout <<"5:00a.m. " << "\t\t" <<"0500 \n";
cout <<"6:00a.m. " << "\t\t" <<"0600 \n";
cout <<"7:00a.m. " << "\t\t" <<"0700 \n";
cout <<"8:00a.m. " << "\t\t" <<"0800 \n";
cout <<"9:00a.m. " << "\t\t" <<"0900 \n";
cout <<"10:00a.m." << "\t\t" <<"1000 \n";
cout <<"11:00a.m." << "\t\t" <<"1100 \n";
cout <<"12:00p.m." << "\t\t" <<"1200 \n";
cout <<"1:00p.m. " << "\t\t" <<"1300 \n";
cout <<"2:00p.m. " << "\t\t" <<"1400 \n";
cout <<"3:00p.m. " << "\t\t" <<"1500 \n";
cout <<"4:00p.m. " << "\t\t" <<"1600 \n";
cout <<"5:00p.m. " << "\t\t" <<"1700 \n";
cout <<"6:00p.m. " << "\t\t" <<"1800 \n";
cout <<"7:00p.m. " << "\t\t" <<"1900 \n";
cout <<"8:00p.m. " << "\t\t" <<"2000 \n";
cout <<"9:00p.m. " << "\t\t" <<"2100 \n";
cout <<"10:00p.m." << "\t\t" <<"2200 \n";
cout <<"11:00p.m." << "\t\t" <<"2300 \n";
cout <<"Midnight " << "\t\t" <<"0000 \n";
}
can somebody tell me whats going wrong. If you test it out use 0600 for departure time and 0900 for arrivaltime.
There are multiple problems in this code. One, in a function like getDays that returns the number of days, you don't need to pass the number of days into the method as a parameter.
Also, since you want a value for days that is greater than 0, you should be checking whether days <= 0 in the while loop. Your current condition, days < 0, will be false if days is set to 0.
getDays would be better written as:
int getDays()
{
int days = 0;
cout << " How many Days did you stay on the trip " <<endl;
cin >> days;
while(days <= 0)
{
cout <<"Please enter a value greater than 0 :D " <<endl;
cin >> days;
}
return days;
}
Also, in getMealExpenses, there seems to be no reason to declare breakFastFee, lunchFee, and dinnerFee as static. This may be the cause of the problem you asked about, since they never get re-initialized to 0 after the first call to getMealExpenses.
Finally, neatly-formatted code is more likely to get helpful responses, because it's easier to read :-)
I think its becouse you are not resetting the breakFastFee, lunchFee, dinnerFee variable to 0 before each execution. So when total+=breakFastFee + lunchFee + dinnerFee; hits it will add values from the previues iteration.
Related
This question already has answers here:
Why does dividing two int not yield the right value when assigned to double?
(10 answers)
Closed 1 year ago.
Hi so im creating a program to have the user input 5 candidates and votes then the program spits back out the winner and percent of each candidate but i cant seem to figure out why the double varible dont show as a number like 40.5 or something just 0 and 100. I am still learning how this works
string candidate[5];
int votes[5];
int total;
double percent[5];
string winner;
cout << "Enter the first candidate: ";
cin >> candidate[0];
cout << "Enter the amount of votes he/she recieved: ";
cin >> votes[0];
cout << endl << "Enter the second candidate: ";
cin >> candidate[1];
cout << "Enter the amount of votes he/she recieved: ";
cin >> votes[1];
cout << endl << "Enter the third candidate: ";
cin >> candidate[2];
cout << "Enter the amount of votes he/she recieved: ";
cin >> votes[2];
cout << endl <<"Enter the fourth candidate: ";
cin >> candidate[3];
cout << "Enter the amount of votes he/she recieved: ";
cin >> votes[3];
cout << endl << "Enter the fifth candidate: ";
cin >> candidate[4];
cout << "Enter the amount of votes he/she recieved: ";
cin >> votes[4];
total = votes [0] + votes[1] + votes[2] + votes[3] + votes[4];
percent[0] = (votes[0] / total * 100);
percent[1] = (votes[1] / total * 100);
percent[2] = (votes[2] / total * 100);
percent[3] = (votes[3] / total * 100);
percent[4] = (votes[4] / total * 100);
if (votes[0] > votes[1] && votes[2] && votes[3] && votes[4])
winner = candidate[0];
if (votes[1] > votes[0] && votes[2] && votes[3] && votes[4])
winner = candidate[1];
if (votes[2] > votes[1] && votes[0] && votes[3] && votes[4])
winner = candidate[2];
if (votes[3] > votes[1] && votes[2] && votes[0] && votes[4])
winner = candidate[3];
if (votes[4] > votes[1] && votes[2] && votes[3] && votes[0])
winner = candidate[4];
cout << "Candidate" << setw(5) << "Votes" << setw(5) << "Percent" << endl;
cout << "------------------------------------------------" << endl;
cout << candidate[0] << setw(5) << votes[0] << setw(5) << percent[0] << endl;
cout << candidate[1] << setw(5) << votes[1] << setw(5) << percent[1] << endl;
cout << candidate[2] << setw(5) << votes[2] << setw(5) << percent[2] << endl;
cout << candidate[3] << setw(5) << votes[3] << setw(5) << percent[3] << endl;
cout << candidate[4] << setw(5) << votes[4] << setw(5) << percent[4] << endl;
cout << "Winner: " << winner << endl;
cout << "Total Votes: " << total;
return 0;}
All of the variables in the calculation on the right hand side of your assignment are ints, so the result is an int.
You would have to convert the operands to doubles to get a double result.
percent[0] = (double(votes[0]) / double(total) * 100);
I'm learning C++ and this is an assignment I have to do, it's complete but my interestEarned is not coming back correctly but the bankBalance is correct so I'm just not displaying interestEarned correctly. "Total Interest Earned: $65.50" is incorrect is supposed to display "$120.50" as my teacher said. What am I doing wrong?
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Variables
int numOfCustomers, numOfMonths = 0;
double bankBalance, depositAmount, withdrawnAmount, interestRate, interestEarned = 0.0;
const int MIN = 0;
// Asking for Number of Customers
cout << "Enter the number of customers: ";
cin >> numOfCustomers;
// Making sure the input was not 0 or lower
while (numOfCustomers <= MIN) {
cout << "==>Number of customers must be at least 1. Try again: ";
cin >> numOfCustomers;
}
// Validating each Customer
for (int c = 1; c < (numOfCustomers + 1); c++) {
// Start of each Customer
cout << "\nCUSTOMER " << c << ":\n";
// Asking for Number of Months --
cout << "Enter the number of months the account has been opened: ";
cin >> numOfMonths;
// Making sure the input was not 0 or lower
while (numOfMonths <= MIN) {
cout << "==>Number of months must be at least 1. Try again: ";
cin >> numOfMonths;
}
// Asking for Starting Balance --
cout << "Enter the starting balance: $";
cin >> bankBalance;
// Making sure the input was not 0 or lower
while (bankBalance < MIN) {
cout << "==>Starting balance can't be negative. Try again: $";
cin >> bankBalance;
}
// Asking for Monthly Interest Rate --
cout << "Enter the monthly interest rate as a decimal (i.e. 0.05 = 5%): ";
cin >> interestRate;
// Making sure the input was not 0 or lower
while (interestRate < MIN) {
cout << "==>Monthly interest rate can't be a nagative. Try again: ";
cin >> interestRate;
}
// Validating each Month
for (int m = 1; m < (numOfMonths + 1); m++) {
// Deposit Amount
cout << "\nEnter deposit amount for Month " << m << ": $";
cin >> depositAmount;
bankBalance = bankBalance + depositAmount;
// Withdrawn Amount
cout << "Enter withdrawn amount for Month " << m << ": $";
cin >> withdrawnAmount;
bankBalance = bankBalance - withdrawnAmount;
// Calculating Interest Earned
interestEarned = bankBalance * interestRate;
// Complete bankBalance
bankBalance = bankBalance + interestEarned;
}
// Account Summary
cout << "\nACCOUNT SUMMARY" << endl;
cout << fixed << setprecision(2);
cout << "Number Months Active: " << numOfMonths << endl;
cout << "Ending Balance: $" << bankBalance << endl;
cout << "Total Interest Earned: $" << interestEarned << endl;
}
system("pause");
return 0;
}
Use another variable that is initialized to zero before the loop. In the loop, add the value of interestEarned to it. - #Peter
My code compiles nicely, but the math formulas that I am using aren't providing the right outcome. I need to calculate the balance, withdrawn, and interest for all 3 months. I am also required to validate user's input. For these purposes I am using nested loops. Please let me know if you spot my mistake. Thank you lovely people!
cout << "Please enter the starting balance: ";
cin >> startBalance;
cout << "Please enter the annual interest rate: ";
cin >> annualInterest;
for (int month = 1; month <= 3; month++) {
do {
cout << setprecision(5);
cout << "Please enter the total amount deposited on month " << month << ": ";
cin >> balance;
if (balance <0) {
goodChoice = false;
cout << "\n\t***ERROR " << balance << " ***";
cout << "*** Choice must be positive***\n" << endl;
}
else {
goodChoice = true;
}
startBalance += balance; //need to calculate the balance for all 3 months
} while (!goodChoice);
do {
cout << setprecision(5);
cout << "Please enter the total amount withdrawn on " << month << ": ";
cin >> withdrawn;
if ( (withdrawn <0) || (withdrawn > startBalance) ) {
goodChoice = false;
cout << "***ERROR " << withdrawn << " ***";
cout << "*** Choice must be positive or greater than the balance***" << endl;
}
else {
goodChoice = true;
}
finalWithdrawn += withdrawn; // the total amount of withdrawn
finalBalance = startBalance - withdrawn;
monthInterest = ((startBalance + finalBalance) / 2) * (annualInterest / 12);
totalInterest += monthInterest; //total interest for all 3 months
endBalance = monthInterest + finalBalance;
} while (!goodChoice);
}
cout << "Total Deposit: " << endBalance << endl;
cout << "Total Withdrawn: " << finalWithdrawn << endl;
cout << "Total Interest: " << totalInterest << endl;
cout << "Final Balance: " << endBalance << endl;
You have a lot of extra variables defined which aren't needed. Also, your interest rate may have been in percentage instead of a decimal number, i.e. 10% = 0.1. Also, your monthInterest is taking an average then applying interest. I wrote this up and it seems to work.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float totalDeposit = 0.0f;
float totalWithdrawn = 0.0f;
float totalInterest = 0.0f;
float totalBalance = 0.0f;
float interestRate = 0.0f;
setprecision(5); //?
cout << "Enter starting balance: ";
cin >> totalBalance;
cout << "Enter annual interest rate (%): ";
cin >> interestRate;
// Convert to monthly and non-percent; i.e. 10% = 0.1 = 10 / 100
interestRate = interestRate / 100.0f / 12.0f;
for (int month = 1; month <= 3; month++)
{
float deposit = -1.0; // Default to an error state
while (deposit < 0.0)
{
cout << "Enter total deposited in month " << month << ": ";
cin >> deposit;
if (deposit < 0.0f)
{
cout << "ERROR: Invalid amount" << endl;
continue;
}
}
float withdrawn = -1.0f; // Default to an error state
while (withdrawn < 0.0f)
{
cout << "Enter total withdrawn in month " << month << ": ";
cin >> withdrawn;
if (withdrawn < 0.0f)
{
cout << "ERROR: Invalid amount" << endl;
continue;
}
}
totalDeposit += deposit;
totalWithdrawn += withdrawn;
totalBalance = totalBalance + deposit - withdrawn;
totalBalance += totalBalance * interestRate;
totalInterest += totalBalance * interestRate;
}
cout << "Total Deposit: " << totalDeposit << endl;
cout << "Total Withdrawn: " << totalWithdrawn << endl;
cout << "Total Interest: " << totalInterest << endl;
cout << "Final Balance: " << totalBalance << endl;
int wait; // Pause so console window doesn't close. Delete this line.
cin >> wait;
return 0;
}
My issue is that I have set up an array to store totals that were calculated from values read from a file. These stored totals are then added together to find the over all average.
This issue is stemming from a 'cin' at the beginning of the program where the user inputs a number and that number is supposed to drive the program by setting how many times the program loops and how many modules are inside the array. The array does not seem to work properly no matter how much I try.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string StudentGrades;
int studentID;
double quiz1;
double quiz2;
double quiz3;
double quiz4;
int total = 0;
double choice;
ofstream outFile;
double numStud=1;
cout << "Enter student ID number, Quiz 1 Grade, Quiz 2 Grade , Quiz 3 Grade, Quiz 4 Grade" << endl;
outFile.open("StudentGrades.txt");
cout << "How many students would you like to enter?" << endl;
cin >> numStud;
for (int x = 0; x < numStud; x++)
{
cout << "Enter student ID: ";
cin >> studentID;
cout << "Enter quiz grade 1: ";
cin >> quiz1;
//cout << quiz1;
cout << "Enter quiz grade 2: ";
cin >> quiz2;
//cout << quiz2;
cout << "Enter quiz grade 3: ";
cin >> quiz3;
//cout << quiz3;
cout << "Enter quiz grade 4: ";
cin >> quiz4;
//cout << quiz4;
cout << endl;
//outFile.open("StudentGrades.txt");
if (outFile.is_open())
{
cout << "inside if/else outFile" << endl;
//outFile << "File successfully open";
outFile << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
}
else
{
cout << "Error opening file";
}
outFile.close();
/*cout << "Enter 0 for no more students. Enter 1 for more students." << endl;
cin >> choice;
if (choice == 1)
continue;
if (choice == 0)
{
outFile.close();
break;
}*/
}
ifstream inFile;
inFile.open("StudentGrades.txt");
int sTotal;
int total[numStud];
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
//cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
total = (quiz1 + quiz2 + quiz3 + quiz4);
sTotal = total[numStud];
double avg = total / 4;
}
system("pause");
return 0;
}
int total[numStud]; is a variable length array and is not standard in C++. If you need an array and you don't know what the size will be then you should use a std::vector. A vector can be used almost exactly as an array can. For example you could would become:
int total;
std::vector<int> studentTotal;
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
//cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
studentTotal.push_back(quiz1 + quiz2 + quiz3 + quiz4); // insert into the vector at the end
total += studentTotal.back(); // get last inserted element
}
Okay so I when I run this code I get that my total is equal to 0 and that
messes up my average and grade.I am not sure what I am doing wrong as the
total += scores function is where it should be, yet it is still not adding up
the scores.
int validateNumber(int, int, int);
in main() function
int num, score, total = 0;
and
validateNumber(num, score, total);
and the definition
int validateNumber(int num, int score, int total) {
while (num < 1 || num > 4) {
cout << over3 << num << " is not between 1 and 4! Try again: ";
cin >> num;
}
system("CLS");
for (int i = 1; i <= num; i++) {
cout << over3 << "Enter score " << i << ": " << endl;
cout << over3 << "Enter a value from 0 to 100: ";
cin >> score;
while (score < 0 || score > 100) {
cout << over3 << score
<< " is not between 0 and 100! Renter the score: " << i << ": ";
cin >> score;
}
total += score;
}
return total;
}
If you want to implement the validate() function like you did here,
validateNumber(num,score,total);
you can make it void and pass the variable total as reference. e.g,
void validateNumber(int num, int score, int &total) {
while (num < 1 || num > 4) {
cout << over3 << num << " is not between 1 and 4! Try again: ";
cin >> num;
}
system("CLS");
for (int i = 1; i <= num; i++) {
cout << over3 << "Enter score " << i << ": " << endl;
cout << over3 << "Enter a value from 0 to 100: ";
cin >> score;
while (score < 0 || score > 100) {
cout << over3 << score
<< " is not between 0 and 100! Renter the score: " << i << ": ";
cin >> score;
}
total += score;
}
}
and the rest would be same...
Otherwise I wouldn't have use 3 arguments in this case. e.g,
int validateNumber(int num) {
int total=0,score;
while (num < 1 || num > 4) {
cout << over3 << num << " is not between 1 and 4! Try again: ";
cin >> num;
}
system("CLS");
for (int i = 1; i <= num; i++) {
cout << over3 << "Enter score " << i << ": " << endl;
cout << over3 << "Enter a value from 0 to 100: ";
cin >> score;
while (score < 0 || score > 100) {
cout << over3 << score
<< " is not between 0 and 100! Renter the score: " << i << ": ";
cin >> score;
}
total += score;
}
return total;
}
and the call:
int num, total;
...
total=validateNumber(num);
Hope it helped...
Are you assuming the function call validateNumber(num,score,total); in line 5 would calculate the total? You should call the function from main function, and assign the return value to a variable, (e.g. total).