I'm trying to complete an assignment but I'm having difficulty with the math expressions and variables in general. I'm trying to make a program that takes user info on groceries and then outputs a receipt. Here is my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
The program output either 0 for all or negatives.
Your calculations must go after you read in the values, not before. You're making your calculations based on uninitialized variables.
A declaration and initialisation like
double firstExt = firstPrice * firstCount;
initialises firstExt to be the product of the current values AT THAT POINT of firstPrice and firstCount.
It doesn't set up some magic so that the value of firstExt is recalculated whenever the values of firstPrice or firstCount are changed.
In your case, firstPrice and firstCount are uninitialised variables when you do this. Accessing values of uninitialised variables of type int gives undefined behaviour.
What you need to do is something like
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
If the value of firstExt is not needed until this point, you can declare it here instead;
double firstExt = firstPrice*firstCount; // do the calculation here
which means any earlier use of firstExt will give a compiler diagnostic.
Related
I'm trying to automatically set the number of the given variables, for example:
char subject1[30];
char subject2[30];
char subject3[30];
float grade1;
float grade2;
float grade3;
cout << "Type in your first subject: " ;
cin >> subject1;
cout << "Type in your second subject: ";
cin >> subject2;
cout << "Type in your third subject: ";
cin >> subject3;
cout << "Type in your grade for: " << subject1 << " :";
cin >> grade1;
cout << "Type in your grade for: " << subject2 << " :";
cin >> grade2;
cout << "Type in your grade for: " << subject3 << " :";
cin >> grade3;
float sum = grade1 + grade2 + grade3;
float average = (sum / 3);
cout << "AVERAGE GRADE";
cout << "************************************" << endl;
cout << subject1 << grade1 << endl;
cout << subject2 << grade2 << endl;
cout << subject3 << grade3 << endl;
cout << "====================================" << endl;
cout << "Average: " << average << endl;
return 0;
The code that calculates it works but I was wondering as how do I put the 3 grades that user inputed. So I don't have to go edit the calculation part every time I add another subject. I'm not sure if I explained well as to what I meant but I hope you understand.
A simple solution would be to store everything in a vector (that's preferred most of the time over the char array you used) an then just loop for the amount of subjects you have.
#include <vector> // need to inlcude this to be able to use vector
#include <iostream>
const int numSubjects = 3;
std::vector<std::string> prefix{"first", "second", "third"};
std::vector<std::string> subjects(numSubjects);
std::vector<float> grades(numSubjects);
for(int i = 0; i < numSubjects; i++) {
std::cout << "Type in your " << prefix[i] << " subject: ";
std::cin >> subjects[i];
std::cout << "Type in your grade for " << subjects[i] << ": ";
std::cin >> grades[i];
}
//afterwards do the calculations
Note that I initialized the vectors with a size of numSubjects that way you can access and write to indices of the vector with the [] operator. If you don't initialize vector with a size then you can use push_back() to insert elements.
assignment at school asks me to find the present value using double, and void. i was able to write my code up to a certain degree but the result is not what i was expecting.. i ended up separating the present value into different section so at the end i'd multiply the amount given with the rest.. any tips on how to make the code actually work the way its supposed to?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double payment,year_term, interest;
double sum;
double Power;
double presentv;
double present;
cout << "Hello, how are you doing?" << endl;
cout << "Please insert a payment amount" << endl;
cin >> payment;
cout << " amount inserted: " << payment << endl;
cout << "Enter number of years" << endl;
cin >> year_term;
cout << " number of years: " << year_term << endl;
cout << "Enter interest rate" << endl;
cin >> interest;
cout << " the interest is: " << interest << "%" << endl;
Presentv = ((1 - (pow((1 + interest),year_term))))/interest;
cout << " the value: " << Presentv << endl;
presentva = payment * Presentv;
cout << " the present value is: " << presentva << endl;
}
(Yes this WAS homework, but already completed, I'm just trying to improve it now for practice)
This is basically a sales calculator, that allows you to have multiple inputs for sales items, then displays the total, sales tax, and grand total.
The modification I'm trying to make, is that I want to be able to SAVE the cost of each number of items in a variable, without them overlapping memory, and then be able to call them above the grand total, so you can see what each item was worth.
===========================================================================
//importing libraries for cin and cout, as well as setw() and setprecision()
#include <iostream>
#include <iomanip>
using namespace std; //sets all code to standard syntax
int main(){ //initializes the main function
//initializing variables
char answer = ' ';
int saleItems = 0;
double saleTax = 0.0;
double grandTotal = 0.0;
double itemValue = 0.0;
double titemValue = 0.0;
double taxPerc = 0.0;
//begins a post-test loop
do {
titemValue = 0.0; //makes sure the accumulator resets WITHIN the loop
//prompts for sale items amount
cout << "How many sales items do you have? : ";
cin >> saleItems;
//creates a loop that displays the prompt for each iteration of saleItems
for (int x = 1; x <= saleItems; x += 1){
cout << "Enter in the value of sales item " << x << " : $";
cin >> itemValue;
titemValue += itemValue; //accumulator for adding up the iterated values
}
//prompts the user to enter a sales percentage
cout << endl << endl;
cout << "Enter in the sales tax percentage(Enter 10 for 10%): ";
cin >> taxPerc;
cout << endl << endl;
//processes the variables after taxPerc has been given
saleTax = titemValue * (taxPerc / 100);
grandTotal = titemValue + saleTax;
//sets decimal precision to 2 places
cout << fixed << setprecision(2);
//displays receipt with the calculated and input values
cout << "********************************************" << endl;
cout << "******** S A L E S R E C E I P T ********" << endl;
cout << "********************************************" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "** Total Sales $" << setw(9) << titemValue << " **" << endl;
cout << "** Sales Tax $" << setw(9) << saleTax << " **" << endl;
cout << "** ---------- **" << endl;
cout << "** Grand Total $" << setw(9) << grandTotal << " **" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "********************************************" << endl << endl << endl;
//prompts user to begin loop again
cout << "Do you want to run this program again? (Y/N):";
cin >> answer;
answer = toupper(answer);
cout << endl << endl;
} while (answer == 'Y');
===========================================================================
So, essentially, I need to be able to save each itemValue to multiple different values without the loop repeating itself, and just replacing them, and I can't really see how I can do that considering the accumulator will just keep looping, and adding up the itemValue values.
Here is one way to use an simple array to store the item values.
Declare an array at the top. Note: you will have to give it a fixed size. There are ways to have a variable size, but they get more complex (such as vectors). It is better to specify the size using a constant, rather than a hard coded number, as you will need the constant later.
const int maxSaleItems = 100;
double itemValues[maxSaleItems];
After you have asked the user for the number of items, max sure they haven't entered a number that is too big.
cout << "How many sales items do you have? : ";
cin >> saleItems;
if (saleItems > maxSaleItems) {
cout << "Sorry, I can only handle " << maxSaleItems << " items.";
continue;
}
Inside the loop where you are inputting the item values, save the item value to the array:
cout << "Enter in the value of sales item " << x << " : $";
cin >> itemValue;
titemValue += itemValue; //accumulator for adding up the iterated values
itemValues[x - 1] = itemValue;
Note the x-1 in the array access - arrays are 0 based (i.e. their index starts from 0). Normally I would loop x from 0 to < saleItems, but I didn't want to change your existing loop.
When printing the receipt, add a loop which prints out all the values (you will need to add formatting):
cout << "** **" << endl;
for (int x = 1; x <= saleItems; x += 1){
cout << "** Item " << x << " $" << itemValues[x-1] << " **" <<endl;
}
cout << "** **" << endl;
As I said in the comments, using std::vector would be better, but if you aren't up to that yet, arrays will do.
Edit: Simple vector example.
To add vectors you need to include the appropriate header:
#include <vector>
No need for maxSaleItems any more, as vectors can grow. Declare the vector variable. The <double> makes it a vector that contains double values:
std::vector<double> itemValues;
Inside the loop, instead of setting the array value for the new item by location, just add it to the end of the vector using push_back.
cout << "Enter in the value of sales item " << x << " : $";
cin >> itemValue;
titemValue += itemValue; //accumulator for adding up the iterated values
itemValues.push_back(itemValue);
The printing receipt code, can be left exactly as it was for the array version, as you can access vectors like arrays:
cout << "** **" << endl;
for (int x = 1; x <= saleItems; x += 1){
cout << "** Item " << x << " $" << itemValues[x-1] << " **" <<endl;
}
cout << "** **" << endl;
There are other changes you could do to make the vector version simpler, but I wanted to change as little as possible.
Onto another program. this is a program that simulates a bank account. I need help with the showing of the balance, withdraw, and deposit. how do i get this to show the final balance after the withdraw/deposit?
#include <iostream>
#include <string>
#include "BACCOUNT.H"
using namespace std;
int main ()
{
double amount = 0.0;
double withrdraw = 0.0;
double deposit = 0.0;
string name;
double startamount = 100.00;
double balance = 0.0;
cout << "name: ";
cin >> name;
cout << "initial balance: " << startamount <<endl;
cout << "deposit? ";
cin >> amount;
cout << "withdraw? ";
cin >> amount;
cout << "balance for " << name << " is " << balance << endl;
system ("pause");
return 0;
}
cout << "balance for " << name () << " is " << balance()
<<endl;
By putting parenthesis after them, you're trying to call name and balance like functions, but they're strings. Remove the parenthesis.
More importantly, what made you think you had to include parenthesis there? There may be a fundamental piece of C++ that you're confused about (functions) that you should seek to fully understand.
You are attempting to call name and balance as functions here:
cout << "balance for " << name () << " is " << balance() <<endl;
^^^^^^^ ^^^^^^^^^
but name is a string and balance is a double. This edit will fix the problem:
cout << "balance for " << name << " is " << balance <<endl;
I am having a couple problems with my code.
First off, with the code like it is, No matter what information I put in, It always returns 0, Any suggestions on where to fix this and how? I believe it has something to do with my Class Employee. How would I go about fixing this?
Second, How do I access the information in int total()? I need to access it for the last bit of code.
Also if you notice anything else that I can do to optimize my program, I welcome your suggestions. I am learning C++ as I go and will always be a Student.
// Datamax.cpp
// Created by Kennith Adkins
#include <iostream>
#include <string>
using namespace std;
class Employee
{
public:
string eName;
float eHours;
float eWage;
float ePay;
float eOvertimeHours;
float eOvertimePay;
float eTotalPay;
float eTotalBaseHours;
float eTotalSalary;
float eTotalOvertimeHours;
int Overtime ()
{
if (eHours > 40)
{
eOvertimeHours = (eHours - 40);
eOvertimePay = (eOvertimeHours * (eWage * 1.5));
ePay = ((eHours - eOvertimeHours) * eWage);
eTotalPay = ePay + eOvertimePay;
}
else
{
ePay = (eHours * eWage);
}
}
int total()
{
eTotalBaseHours = (employee1.eHours - employee1.eOvertimeHours) + (employee2.eHours - employee2.eOvertimeHours) + (employee3.eHours - employee3.eOvertimeHours);
eTotalSalary = (employee1.eTotalPay + employee2.eTotalPay + employee3.eTotalPay);
eTotalOvertimeHours = (employee1.eOvertimeHours + employee2.eOvertimeHours + employee3.eOvertimeHours);
}
} employee1, employee2, employee3;
// Start the main program here
int main()
{
// Gretting
cout << "Welcome to the Employee Pay Center\n";
// Employee1 information
cout << "Enter the employee name: ";
cin >> employee1.eName;
cout << "Enter the hours worked: ";
cin >> employee1.eHours;
cout << "Enter his or her hourly wage: ";
cin >> employee1.eWage;
cout << endl; // Adding a blank line to space the information out
// Employee2 information
cout << "Enter the employee name: ";
cin >> employee2.eName;
cout << "Enter the hours worked: ";
cin >> employee2.eHours;
cout << "Enter his or her hourly wage: ";
cin >> employee2.eWage;
cout << endl; // Adding a blank line to space the information out
// Employee3 information
cout << "Enter the employee name: ";
cin >> employee3.eName;
cout << "Enter the hours worked: ";
cin >> employee3.eHours;
cout << "Enter his or her hourly wage: ";
cin >> employee3.eWage;
cout << endl; // Adding a blank line to space the information out
// Returning the information to the Employeer
cout << "Employe Name ............ = " << employee1.eName << "\n";
cout << "Base Pay................. = " << employee1.ePay << "\n";
cout << "Hours in Overtime........ = " << employee1.eOvertimeHours << "\n";
cout << "Overtime Pay Amount...... = " << employee1.eOvertimePay << "\n";
cout << "Total Pay................ = " << employee1.eTotalPay << "\n\n";
cout << "Employe Name ............ = " << employee2.eName << "\n";
cout << "Base Pay................. = " << employee2.ePay << "\n";
cout << "Hours in Overtime........ = " << employee2.eOvertimeHours << "\n";
cout << "Overtime Pay Amount...... = " << employee2.eOvertimePay << "\n";
cout << "Total Pay................ = " << employee2.eTotalPay << "\n\n";
cout << "Employe Name ............ = " << employee3.eName << "\n";
cout << "Base Pay................. = " << employee3.ePay << "\n";
cout << "Hours in Overtime........ = " << employee3.eOvertimeHours << "\n";
cout << "Overtime Pay Amount...... = " << employee3.eOvertimePay << "\n";
cout << "Total Pay................ = " << employee3.eTotalPay << "\n\n";
cout << "*******************************************************\n";
cout << "*****************EMPLOYEE SUMMARY DATA*****************\n";
cout << "*******************************************************\n";
cout << "** Total Employee Salaries............ " << "**\n";
cout << "** Total Employee Hours............... " << "**\n";
cout << "** Total Overtime Hours............... " << "**\n";
cout << "*******************************************************\n";
cout << "*******************************************************\n";
return 0;
}
Hey Guys, Thanks for the help. I have most of it done now. It is displaying all the information. I am now just working on getting it to display the Employee Summary Data. I revamped my code to make it cleaner because I was trying every suggestion given to me as I learn best by hands on.
That's what you get for using non-initialized variables. You have set no value to your class members, you can't expect the compiler to guess what is your employee's name or total pay.
You need to use the form:
object name.member name = value
Of course, you should call the functions before outputting results that are supposed to be produced by these functions:
employee1.Overtime();
employee2.Overtime();
employee3.Overtime();