i'm a beginner in C++ and just wanted to know if it is possible for me to put the calculation in the last "for" loop that uses the name,amount and weight from the "Product" class to calculate the total and price in another class that would be titled "Price".
Sorry for the weird question i am just confused as to how to use classes with one another and if it is possible to do so...
#include <iostream>
#include <string>
using namespace std;
class Product
{
public:
string name;
int amount;
float weight;
void get()
{
cout << "Give product name,amount and weight : " << endl;
cin >> name >> amount >> weight;
}
void print()
{
cout << name << " - "<< amount<<" , " <<weight <<" kg"<< endl;
cout << "--------" << endl;
};
};
int main()
{
Product p[100];
int n;
cout << "Give the number of products you want to get : " << endl;
cin >> n;
for (int i = 0; i < n; i++)
{
p[i].get();
}
cout << "Product display: " << endl;
for (int i = 0; i < n; i++)
{
p[i].print();
}
float total = 0;
for (int i = 0; i < n; i++)
{
cout << "\nPrice of " << p[i].name << " " << p[i].amount * p[i].weight << " $" << endl;
total = p[i].amount * p[i].weight + total;
}
cout << "\nTotal: " << total << "$" << endl;
cin.get(); cin.get();
return 0;
}
Its fine to have such questions when you are a beginner. There are few points I would to mention.
In your example there is no need of creating a separate class just
for calculating the price. Calculation of price is a flow/method/set
of instructions. So the logic of calculation of price should be a
method and that too in the same class i.e. Product.
Secondly here the total price for for all the products is common for
the class i.e. it is not different for different objects of the class. So
here you need to create a static variable under the class which will
carry the total price of all the products.
You can just create a static function in the Product class and pass
the array of product as an argument and loop through the products to
calculate the total price and store it in the static variable.
Hope this clears your doubt.
Related
The program should prompt the user to enter the number of jars sold for each type.The program should produce a report that displays sales for each salsa type, total sales, and the names of the highest selling and lowest selling products.
#include <iostream>
#include<string>
using namespace std;
int main()
{
const int SIZE=5;
string salsa_names[SIZE] = { "mild","medium","sweet","hot","zesty" },name1,name2;
double number_of_jars_sold[SIZE],total=0;
cout << "enter the number of jars sold for each of different types of salsa\n";
for (int i = 0; i < SIZE; i++)
{
cout <<"The salsa names are :"<<"'"<<salsa_names[i]<<"'";
cin >> number_of_jars_sold[i];
total += number_of_jars_sold[i];
}
double large=number_of_jars_sold[0],small=number_of_jars_sold[0];
cout << "The sales for each of salsa type is ="<<endl;
for (int i=0;i<SIZE;i++)
{
cout << salsa_names[i] << " : " << number_of_jars_sold[i] << endl;
}
cout << "total sale is equal to" << total << endl;
for (int i = 0; i < SIZE; i++)
{
if (large < number_of_jars_sold[i])
{
large = number_of_jars_sold[i];
name1=salsa_names[i];
}
}
for (int j = 0; j < SIZE; j++)
{
if (small > number_of_jars_sold[j])
{
small = number_of_jars_sold[j];
name2 = salsa_names[j];
}
}
cout << "The name of highest selling product is : " << name1 << endl;
cout << "The name of lowest selling product is : " << name2 << endl;
return 0;
}
Edited::
you should initialize small and large to zero first, add an if condition before this line if (small > number_of_jars_sold[j]):
if(small == 0), so you will have minimum value in small variable.
I'm trying to sort for the top and second top value of totalRevenue and its name. I've tried to sort them in descending order this way but I could not figure it out how to make it work. Can anyone please help me out?
First two entries:
1002 Hammer 23.65 203
1024 Nails 6.95 400
Here is the code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Structure to hold statistics
struct Selling {
int productNumber;
string name;
double price;
int soldNumber;
double totalRevenue[];
};
int main()
{
ifstream statFile;
string productName;
double price;
int productNumber, soldNumber;
Selling *productArray[100];
Selling *aSelling;
int numProduct = 0;
int man = 0;
statFile.open("sales.txt");
while (numProduct < 100 && statFile >> productNumber >> productName >> price >> soldNumber)
{
Selling *aSelling = new Selling;
aSelling->productNumber = productNumber;
aSelling->name = productName;
aSelling->price = price;
aSelling->soldNumber = soldNumber;
aSelling->totalRevenue[] = aSelling->price * aSelling->soldNumber;
productArray[numProduct++] = aSelling;
//cout << aSelling->productNumber<< " " << aSelling->name << " " << aSelling->price << " " << aSelling->soldNumber << " " << aSelling->totalRevenue << endl;
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (aSelling->totalRevenue[i] > aSelling->totalRevenue[j]) {
man = aSelling->totalRevenue[i];
aSelling->totalRevenue[i] = aSelling->totalRevenue[j];
aSelling->totalRevenue[i] = man;
}
}
}
for (int i = 0; i < 2; i++) {
cout << "The top selling product is " << aSelling->name << "with total sales of " << aSelling->totalRevenue[i] << endl;
cout << "The second top selling product is " << aSelling->name << "with total sales of " << aSelling->totalRevenue[i - 1] << endl;
}
}
And there is an unexpected expression error at the line aSelling->totalRevenue[] = aSelling->price * aSelling->soldNumber; which I don't understand.
There is some confusion on the arrays to sort:
you should define totalRevenue as a double, not an array of doubles,
should be sort the first numProduct elements of the array productArray based on the criteria totalRevenue and name, the order is determined by the comparison operator used. Only compare the second criteria if the first criteria give equal values.
Here is a modified version:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Structure to hold statistics
struct Selling {
int productNumber;
string name;
double price;
int soldNumber;
double totalRevenue;
};
int compareSellings(const Selling *a, const Selling *b) {
// sort in decreasing order of totalRevenue
if (a->totalRevenue > b->totalRevenue) return -1; // a comes before b
if (a->totalRevenue < b->totalRevenue) return +1; // b comes before a
// sort in increasing order of name for the same totalRevenue
if (a->name < b->name) return -1; // a comes before b
if (a->name > b->name) return +1; // b comes before a
return 0;
}
int main() {
ifstream statFile;
string productName;
double price;
int productNumber, soldNumber;
Selling *productArray[100];
int numProduct = 0;
statFile.open("sales.txt");
while (numProduct < 100 && statFile >> productNumber >> productName >> price >> soldNumber) {
Selling *aSelling = new Selling;
aSelling->productNumber = productNumber;
aSelling->name = productName;
aSelling->price = price;
aSelling->soldNumber = soldNumber;
aSelling->totalRevenue = price * soldNumber;
productArray[numProduct++] = aSelling;
//cout << aSelling->productNumber<< " " << aSelling->name << " "
// << aSelling->price << " " << aSelling->soldNumber << " "
// << aSelling->totalRevenue << endl;
}
for (int i = 0; i < numProduct; i++) {
for (int j = 0; j < numProduct; j++) {
if (compareSellings(productArray[i], productArray[j]) > 0) {
Selling *aSelling = productArray[i];
productArray[i] = productArray[j];
productArray[j] = aSelling;
}
}
}
cout << "The top selling product is " << productArray[0]->name
<< ", with total sales of " << productArray[0]->totalRevenue << endl;
cout << "The second selling product is " << productArray[1]->name
<< ", with total sales of " << productArray[1]->totalRevenue << endl;
return 0;
}
Further remarks:
you might use a more efficient sorting method
you should free the allocated objects
you should use <algorithms> and dynamic arrays of objects instead of allocating the objects with new and manipulating naked pointers.
you should handle exceptions
I am currently making a cash register that inputs 5 values and then outputs those same 5 values on a receipt with the item tax and subtotal. I then have to add together all the item costs, tax costs and so on to produce a total. So Far I have created code to intake five values and set the frame for my receipt. The issue I have is I have no idea how to get all the values entered from the initial loop and put them on the receipt. The only value that is retained is the final value I input. I'm pretty new so excuse my code and if it's not obvious for myself! Appreciate the help!
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double taxRate = 0.07;
double subtotal = 0;
double total = 0;
float item;
float cost;
float counter = 0;
while (counter != 5) {
for (int num=0; num < item; num++) {
}
counter++;
std::cout <<"Enter the cost of the item: ";
std::cin>>item;
}
cout << endl;
cout << setw(10) << "Item Cost"
<< setw(11) << "Item Tax"
<< setw(19) << "Item Subtotal\n";
cout << "----------------------------------------\n";
std::cout.precision(2);
std::cout.setf(std::ios::fixed);
cout << setw(10) << item << setw(11) << item * taxRate<< setw(17) << (item*taxRate)+item << endl;
return 0;
}
You should start by reading on what vectors are and how they work. Get rid of the while loop. You only need 2 for loops to accomplish the task with the way your code is set up.
vector<float> cash;
......
......
for (int i = 0; i < 5; i++)
{
cout << "Enter the cost of the item: ";
cin >> item;
//push items into vector here
}
.....
.....
for (int i = 0; i < cash.size(); i++)
{
// output like you were doing but with your vector elements
}
With that skeleton code you should be able to accomplish what you want with a little research
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have the following assignment for my Programming I class:
Prompt for the price of each item. Store each item price in the array named prices. When the user has reached $1,000 or 5 items,
print out how much was spent, how many items were bought, how much is left, and the average price.
Print a table of the prices of the items bought.
My original attempt got very mangled:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int cost = 1;
int total = 0;
int i = 0;
const int MAXNUM = 5;
int prices[MAXNUM];
while (total < 1000 && cost !=0 && i < MAXNUM)
{
for (int x = 0; i < MAXNUM; i++)
{
cout << "Please enter the price of the item you are purchasing:"<< endl << i+1 << "." <<"$";
cin >> cost;
total+=cost;
}
// total += cost;
}
/*
// cout << \n << "Name: ";
// cin >> name;
} */
cout << "You spent $" << total << " by purchasing " << /* **************** << */ " items, you have $" << 1000-total <</* " leftover, and your average price was $" << total/ ******** << */ "." << endl;
return 0;
}
So I started over from scratch and so far I have this:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
const int NUMELS = 5;
int i, prices[NUMELS];
string items [NUMELS];
for (i = 0; i < NUMELS; i++)
{
cout << "Enter the name of the product: ";
cin >> items[i];
cout << "Enter the price of the product: $";
cin >> prices[i];
}
cout << endl;
for (i = 0; i < NUMELS; i++)
cout << items[i]<< " cost you $"<< prices[i]<< endl;
return 0;
}
My biggest difficulty right now is trying to have the program check so that the price doesn't go over $1000 (Which I've written a program for in the past) while ALSO checking to make sure the user purchases no more than 5 items. There are more steps after all of this but once I figure out the base I should be able to build the rest on my own.
I tried putting if (acc > 1000)
break; at the end of my for loop, but then this happened...
Thanks in advance!!
Your attempt using break was not a bad idea, but the loop that prints the result should use the amount of elements entered , not the fixed value 5.
int main()
{
const int NUMELS = 5;
int TotalPrice = 0;
int i, j, prices[NUMELS];
string items [NUMELS];
for (i = 0; i < NUMELS; i++)
{
if (TotalPrice >= 1000)
break;
cout << "Enter the name of the product: ";
cin >> items[i];
cout << "Enter the price of the product: $";
cin >> prices[i];
TotalPrice += prices[i];
}
cout << endl;
for (j = 0; j < i; j++)
cout << items[j]<< " cost you $"<< prices[j]<< endl;
return 0;
}
if I get you, you'll like to also check if the user has exceeded $1000 in the loop that checks if user has bought 5 item. If that is, maybe this should work.
for (int i = 0, exceed = 0; i < NUMELS && exceed < 1000; i++){
cout << "Enter the name of the product: ";
cin >> items[i];
cout << "Enter the price of the product: $";
cin >> prices[i];
exceed += prices[i];
}
Try this
you can use
while(){}
cycle
write something like this
int count = 0, sum = 0;
while(count < 5 && sum <= 1000)
{
cout << "Enter the name of the product: ";
cin >> items[count ];
cout << "Enter the price of the product: $";
cin >> prices[count ];
sum += prices[count ];
count++;
}
cout << endl;
for (int i = 0; i < count; i++)
cout << items[i]<< " cost you $"<< prices[i]<< endl;
So I'm trying to create an array that contains some user inputted names, and then associate those names with letter grades from tests (ex: A, B, C, D, F). My question is, how would I use an array to accept the user inputted names?
EDIT:
Sorry this is a bit long, I don't know what part to put that would help out. Totally new to C++ and I can't seem to find anything online regarding the matter, lol.
Here is some code. This program currently asks the user for test scores, then displays and drops the lowest test score, and finally, calculates the average of the scores without the lowest one. The end goal is to ask the user for 5 students names, and 4 scores for each student, then dropping the lowest score for each student and calculating the averages of ALL scores inputted regardless of student.
#include <iostream>
#include <string>
using namespace std;
void getScore(int &);
int findLowest(int [], int);
void calcAverage(int [], int);
int main () {
const int NUM_SCORES = 5;
int scores[NUM_SCORES];
cout << "Welcome to test averages." << endl;
cout << "Please enter scores for " << NUM_SCORES << " students." << endl;
cout << endl;
for (int i = 0; i < NUM_SCORES; i++) {
getScore(scores[i]);
}
for (int i = 0; i < NUM_SCORES; i++) {
cout << "Score " << (i + 1) << ": " << scores[i] << endl;
}
cout << endl;
cout << "The lowest of these scores is " << findLowest(scores, NUM_SCORES) << endl;
calcAverage(scores, NUM_SCORES);
return 0;
}
void getScore(int & s) {
s = -1;
cout << "Please enter a test score: ";
cin >> s;
while (s < 0 || s > 100) {
cout << "Score range must be from 0-100" << endl;
cout << "Please re-enter a score: ";
cin >> s;
}
}
int findLowest(int theArray [], int theArraySize) {
int lowest = theArray[0];
for (int i = 1; i < theArraySize; i++) {
if (theArray[i] < lowest) {
lowest = theArray[i];
}
}
return lowest;
}
void calcAverage(int theArray [], int theArraySize) {
int sum = 0;
for (int i = 0; i < theArraySize; i++) {
sum += theArray[i];
}
double average = (sum - findLowest(theArray, theArraySize)) / (theArraySize - 1.0);
cout << "The average is " << average << endl;
}
Try getline from #include <string>
std::string names[5];
for (int i = 0; i < 5; ++i){
getline(std::cin, names[i]);
}