Printing a receipt using parallel arrays c++ - c++

I have been given this assignment for a lab project, and I have everything working until it gets to the receipt part. The issues I am having are 1) printing the incorrect menu items ordered, and 2) getting -42........ number for the pricing. I've looked through this several times and have spoken with others in the class. This is where we are ALL having issues. My TA said to use array[array1[counter]] for this section, but it doesn't seem to work. Can you help me focus on where things are seriously incorrect?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int NUM_MENU_ITEMS = 10; // num items on the menu
const int MAX_ORDER_ITEMS = 5; // max num of items per order
const double DISCOUNT_MIN = 20.00; // min subtotal to get discount
const double DISCOUNT_RATE = 0.25; // disc rate for highest-priced item
// Menu: parallel constant arrays
const string menuItem[NUM_MENU_ITEMS] = {
"Burger", "Hot Dog", "Chicken Fingers", "Fries",
"Tots", "Tea", "Coke", "Diet Coke", "Water", "Cookies" };
const double menuPrice[NUM_MENU_ITEMS] = {
3.50, 2.75, 4.25, 2.50, 3.25,
1.00, 1.25, 1.25, 0.25, 2.50 };
int main()
{
// Order: parallel partial arrays of items ordered
// Each item has an item number, quantity ordered, and total price
// TODO: declare a list of item numbers
// TODO: declare a list of quantities
// TODO: declare a list of item prices (menu price X quantity)
// TODO: declare other variables as needed
double total, subtotal, discount;
// receipt line data
string recName;
int recQty;
int j = 0;
double recPrice;
// print menu
cout << "MENU:\n" << fixed << setprecision(2);
cout << "## Item Price\n";
cout << "-- --------------- -------\n";
// TODO: write a loop to print the menu
int i = 0;
int itemNumber[NUM_MENU_ITEMS] = {
0,1, 2, 3, 4, 5, 6, 7, 8, 9 };
while (i <= 9)
{
cout << setw(2) << itemNumber[i] << " " <<
left << setw(15) << menuItem[i] <<
right << " $ " << setw(5) << menuPrice[i] << endl;
i++;
}
cout << endl;
// get order
int counter = 0;
int itemQuantity[MAX_ORDER_ITEMS];
double itemPrice[MAX_ORDER_ITEMS];
int itemOrder[MAX_ORDER_ITEMS];
string itemName[MAX_ORDER_ITEMS];
do {
cout << "Enter quantity and menu item number (0 0 to end):\n";
cout << "Item 0: ";
cin >> itemQuantity[counter] >> itemOrder[counter];
itemOrder[counter] = itemNumber[counter];
itemPrice[counter] = menuPrice[itemOrder[counter]] *
itemQuantity[counter];
itemName[counter] = menuItem[itemOrder[counter]];
counter++;
} while (counter < MAX_ORDER_ITEMS && itemQuantity[counter] != 0);
// TODO: repeat inputs until quantity is 0 or MAX_ORDER_ITEMS exceeded
//{
// //TODO: add an item to the order parallel arrays
// cout << "Item " << menuItem[i] << ": ";
// cin >> itemQuantity[i] >> itemPrice[i];
//}
double maxItemPrice = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
if (itemPrice[counter] > maxItemPrice)
maxItemPrice = i;
}
// find the subtotal price
// TODO: use a loop to calculate the sum of all order prices
subtotal = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
subtotal = subtotal + itemPrice[counter];
}
// discount highest order line by 25% when total > $20
if (subtotal >= DISCOUNT_MIN)
{
// TODO: add a loop to find the maximum item price
discount = DISCOUNT_RATE * maxItemPrice;
}
else
discount = 0;
// calculate the total price
total = subtotal - discount;
// print the receipt
cout << "\n----------------------------\n";
cout << "Item Qty Price\n";
cout << "--------------- --- -------\n";
// TODO: use a loop to print the lines of the receipt
i = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
recName = itemName[i];
recQty = itemQuantity[i];
recPrice = itemPrice[menuPrice[i]];
cout << left << setw(15) << recName << " "
<< right << setw(3) << recQty << " $"
<< setw(6) << recPrice << endl;
}
cout << "\nSubtotal: $" << setw(6) << subtotal << endl;
cout << "Discount: $" << setw(6) << discount << endl;
cout << "Total Price: $" << setw(6) << total << endl << endl;
system("pause");
return 0;
}

In this line in the do while loop:
} while (counter < MAX_ORDER_ITEMS && itemQuantity[counter] != 0);
you have already incremented counter so your while loop is checking a part of the
itemQuantity
array that has not been input yet.
Also, here
double maxItemPrice = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
if (itemPrice[counter] > maxItemPrice)
maxItemPrice = i;
}
counter is a variable used previously and has not been updated. What is counter representing, and what is i?
And again here,
subtotal = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
subtotal = subtotal + itemPrice[counter];
}
Counter is still the same as it was left in the do while loop. Here it should be
subtotal = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
subtotal = subtotal + itemPrice[i];
}
Check array parameters closely and make sure what's written is doing what you want it to do. Best of luck!

Related

Summing elements from a copied array in c++

I've written a program that creates a restaurant menu through a text file, is opened up in another program and used to create a customer order.
I have a function which is needed to create the total amount at the end however the total sum is never produced, the program instead produces the total from itemPrice * itemQuantity and prints that instead of summing the final total.
I have the items saved in the menuItem array and am trying to copy them into a billingItems array to sum the prices in parallel. What step am I missing in order for total to sum up the prices, so total at the bottom would equal 44 (16+28) ?
Thank you
Creating the order in main():
int main(){
int i;
Item billingItem[MAX_ORDER];
Item menuItem[MAX_ORDER];
int itemNumber;
int itemQuantity;
int billOpt;
std::ofstream transactionFile;
transactionFile.open("transactionFile.txt");
int count = 0;
for(i = 0; i < MAX_ORDER; i++) {
std::cout << "Item number: ";
std::cin >> itemNumber;
i = itemNumber - 1;
std::cout << "Quantity: ";
std::cin >> itemQuantity;
menuItem[i].saveItemDetails(transactionFile);
std::cout << "\nWould you like to add another item?" << std::endl;
std::cout << "1. Yes\n2. No" << std::endl;
std::cin >> billOpt;
if (billOpt <= 0 | billOpt > 2) {
std::cout << "Error. Please enter a valid number: ";
std::cin >> billOpt;
}
if(billOpt == 2) { break; }
}
billingItem[i] = menuItem[i];
billingItem[i].calculateVAT(count, itemQuantity);
transactionFile.close();
the function within the implementation file:
void Item::calculateVAT(int count, int itemQuantity){
double total = 0.0;
double newItemPrice;
newItemPrice = itemPrice * itemQuantity;
total = newItemPrice + total;
//extra couts to see what is happening
std::cout << "ITEM QUANTITY" << itemQuantity <<"\n";
std::cout << "TOTAL" << total <<"\n";
}
what is produced when running the program:
Item: 2| Category: Meat| Description: Pork Chops| Price: £8
COUNT3
ITEM QUANTITY2
TOTAL16
Item: 3| Category: Meat| Description: Ribs| Price: £14
COUNT4
ITEM QUANTITY2
TOTAL28
You could declare total as static in the function so it is only initialized once.
void Item::calculateVAT(int count, int itemQuantity){
static double total = 0.0;
double newItemPrice;
newItemPrice = itemPrice * itemQuantity;
total += newItemPrice ; //
//extra couts to see what is happening
std::cout << "ITEM QUANTITY" << itemQuantity <<"\n";
std::cout << "TOTAL" << total <<"\n";
}
Another solution would be to declare a total variable in the main and modify your function signature.
That would imply printing total from your main.
calculateVAT function :
double Item::calculateVAT(int count, int itemQuantity)// No more void
{
double total = 0.0; // this one only serves in the function scope
double newItemPrice;
newItemPrice = itemPrice * itemQuantity;
total = newItemPrice + total;
//extra couts to see what is happening
std::cout << "ITEM QUANTITY" << itemQuantity <<"\n";
std::cout << "TOTAL" << total <<"\n";
return total; // this number will add up in the main
}
Your main :
int main(){
int i;
Item billingItem[MAX_ORDER];
Item menuItem[MAX_ORDER];
int itemNumber;
int itemQuantity;
int billOpt;
double total = 0.0; // this here will serve as the sum of all your items prices
std::ofstream transactionFile;
transactionFile.open("transactionFile.txt");
int count = 0;
for(i = 0; i < MAX_ORDER; i++) {
std::cout << "Item number: ";
std::cin >> itemNumber;
i = itemNumber - 1;
std::cout << "Quantity: ";
std::cin >> itemQuantity;
menuItem[i].saveItemDetails(transactionFile);
std::cout << "\nWould you like to add another item?" << std::endl;
std::cout << "1. Yes\n2. No" << std::endl;
std::cin >> billOpt;
if (billOpt <= 0 | billOpt > 2) {
std::cout << "Error. Please enter a valid number: ";
std::cin >> billOpt;
}
if(billOpt == 2) { break; }
}
billingItem[i] = menuItem[i];
total += billingItem[i].calculateVAT(count, itemQuantity); // modified here``
std::cout << "TOTAL" << total << std::endl;
transactionFile.close();
For reference, I have made a simple code with a basic situation :
void calculateVAT(int count, int itemQuantity) { // Static version, is initialized only once and then only gets updated
static double total = 0;
double newItemPrice;
newItemPrice = 10 * itemQuantity;
total += newItemPrice ;
//extra couts to see what is happening
std::cout << "ITEM QUANTITY " << itemQuantity << "\n";
std::cout << "TOTAL from function " << total << "\n";
}
double d_calculateVAT(int count, int itemQuantity) { // Non void version, returns a sum to a variable in the main
double sum = 0;
double newItemPrice;
newItemPrice = 10 * itemQuantity;
sum += newItemPrice;
return sum;
}
int main()
{
int itemQty = 5;
double sum = 0; // if you want to call it from the main
calculateVAT(0, 4); // void version with static - will update its total variable as 40
calculateVAT(0, 7); // void version with static - will update its total variable as 40 + 70 = 110
sum+=d_calculateVAT(0, 4); // double version - will return sum = 40
sum+=d_calculateVAT(2, 7); // double version - will return sum + 70 = 110
std::cout << "TOTAL from main " << sum << std::endl;
while (1)
{ }
return 0;
}
Also, maybe it's for another purpose, but I don't see the point of the variable "count" sent to calculateVAT, it's not used in the function.

How can I sort in descending order?

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

Double variable outputs 32767 always instead of user input

I'm writing code that asks about rainfall each month, then outputs yearly total, monthly average, min, and max rain month (index). My code is almost complete, except that instead of outputting the max value the output always shows the max range of the variable type 32767 (e.g. if rain is 70mm and maximum, console shows 32767 always). Thanks for your help. I'm self-learning.
I have tried the following code.
#include<iostream>
using namespace std;
int main(){
const int numMonths = 3;
double monthlyRain[numMonths]={0,0,0};
string monthName[numMonths]= {"Jan", "Feb", "Mar"};
int count = 0;
int indexWettest = 0;
int indexDriest = 0;
double yearTotal=0, monthlyAverage=0;
double monthHighest;
double monthLowest;
monthLowest = monthlyRain[0];
monthHighest = monthlyRain[0];
// enter monthly rain;
for (int count=0; count < numMonths; count++){
cout << "Please enter amount of rain in " << monthName[count] << endl;
cin >> monthlyRain[count];
}
// print month and corresponding rain amount;
cout << "Month --- Rain(mm)" << endl;
for (int count = 0; count < numMonths; count++){
cout << monthName[count] << " " << monthlyRain[count] << endl;
}
// calculate year total;
for (int count = 0; count < numMonths; count++){
yearTotal += monthlyRain[count];
}
// calculate average monthly rainfall;
monthlyAverage = yearTotal/numMonths;
// find month with lowest rainfall;
// find month with highest rainfall;
for (int count = 0; count < numMonths; count++){
if (monthlyRain[count] > monthHighest){
monthHighest = monthlyRain[count+1];
indexWettest = count;
}
}
// PROBLEM IS HERE!;
for (int count = 0; count < numMonths; count++){
if (monthlyRain[count] < monthLowest){
monthLowest = monthlyRain[count];
indexDriest = count;
}
}
cout << "Total yearly rain fall is: " << yearTotal << endl;
cout << "Average monthly rainfall is: " << monthlyAverage << endl;
cout << "The driest month is " << monthName[indexDriest] << " with rain amount of " << monthLowest << endl;
cout << "The wettest month is " << monthName[indexWettest] << " with rain amount of " << monthHighest << endl; //<< monthName[indexWettest];
return 0;
}
Expected result is the user input.
Read compiler warnings.
main.cpp:35:19: warning: 'yearTotal' may be used uninitialized in this function [-
Wmaybe-uninitialized]
yearTotal += monthlyRain[count];
Line that declares yearTotal should be double yearTotal = 0;
Same with other variables. Always initialize them.

Why isn't my array incrementing properly?

I am in a C++ class and I am having trouble with the project. The idea of the project is to create an ordering application using structs and arrays. As far as I can tell the program is working as intended except for the how many items of each item the person ordered part of my printMenu function. If I am mistaken and or you find more errors please let me know.
Here is the code:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
struct dinnerItemType
{
string dinnerItem;
double dinnerPrice;
int dinnerOrdered;
};
void getFood(dinnerItemType ourMenu[], int &size);
void printMenu(dinnerItemType ourMenu[], int size);
void printCheck(dinnerItemType ourMenu[], int size);
//Defines the global tax constant of 6%
const double TAX = 0.06;
int main()
{
dinnerItemType ourMenu[150];
int size = 0;
getFood(ourMenu, size);
printMenu(ourMenu, size);
printCheck(ourMenu, size);
system("pause");
return 0;
}
void getFood(dinnerItemType ourMenu[], int &size)
{
ourMenu[0].dinnerItem = "Chicken Sandwich";
ourMenu[0].dinnerPrice = 4.45;
ourMenu[0].dinnerOrdered = 0;
ourMenu[1].dinnerItem = "Fries";
ourMenu[1].dinnerPrice = 2.47;
ourMenu[1].dinnerOrdered = 0;
ourMenu[2].dinnerItem = "Truffle Fries";
ourMenu[2].dinnerPrice = 0.97;
ourMenu[2].dinnerOrdered = 0;
ourMenu[3].dinnerItem = "Filet 8oz";
ourMenu[3].dinnerPrice = 11.99;
ourMenu[3].dinnerOrdered = 0;
ourMenu[4].dinnerItem = "Fruit Basket";
ourMenu[4].dinnerPrice = 2.44;
ourMenu[4].dinnerOrdered = 0;
ourMenu[5].dinnerItem = "Tea";
ourMenu[5].dinnerPrice = 0.69;
ourMenu[5].dinnerOrdered = 0;
ourMenu[6].dinnerItem = "Water";
ourMenu[6].dinnerPrice = 0.25;
ourMenu[6].dinnerOrdered = 0;
size = 7;
}
void printMenu(dinnerItemType ourMenu[], int size)
{
int number;
int amount;
cout << "Welcome to the restraunt here are your menu items: \n";
for (int i = 0; i < size; i++)
{
cout << (i + 1) << ")";
cout << ourMenu[i].dinnerItem
<< "$"
<< ourMenu[i].dinnerPrice
<< endl;
}
cout << "To order just type in the number associated with the menu item and hit enter.\n"
<< "Once you have completed your order just type in 0 to go to checkout.\n";
cin >> number;
while (number != 0)
{
if (number >= 1 && number <= 8)
{
ourMenu[number - 1].dinnerOrdered++;
}
else
{
cout << "The number does not coorispond with a menu item please try again.\n";
}
cout << "To order just type in the number associated with the menu item and hit enter.\n"
<< "Once you have completed your order just type in 0 to go to checkout.\n";
cin >> number;
}
}
void printCheck(dinnerItemType ourMenu[], int size)
{
double total = 0;
cout << "Your Bill: ";
for (int i = 0; i < size; i++)
{
if (ourMenu[i].dinnerOrdered > 0)
{
total += ourMenu[i].dinnerPrice;
}
}
cout << "Tax: $ " << fixed << setprecision(2) << (total * TAX);
cout << " Ammount Due: $" << (total + (total * TAX)) << endl;
cout << "Thank you come again!" << endl;
}
This line:
total += ourMenu[i].dinnerPrice;
is only adding the cost of one meal to the total, regardless of how many times that meal is ordered.
To fix it: simply multiple the price by the number of times it is ordered:
total += ourMenu[i].dinnerPrice * ourMenu[i].dinnerOrdered;

C++ Setting the number of array elements within a class

Hi I am working on a class for a weather station that asks a user to input variables and it passes the hours to an array: calculating the values for average, Highs and lows. I got it to work but want to make the array[elements] private. Is it possible to do this?
Here is my code so far. Thank you in advance for any help.
Brian
#include <iostream>
#include <iomanip>
using namespace std;
class WeatherStation
{
public:
WeatherStation();
void GetATemperatures(int[], int);
void DisplayATemperatures( int[], int);
void arrayCalcs(int[], int);
private:
static const int aTemps = 24;
static const int atemps[aTemps];
};
WeatherStation::WeatherStation()
{
int atemps[aTemps];
}
void WeatherStation::GetATemperatures(int atemps[], int aTemps)
{
for (int i = 0; i < aTemps; i++ )
{
cout << "Please enter the temperature for " << i << ":00 ";
while(true)
{
cin >> atemps[i];
if(atemps[i] >= -50 && atemps[i] <= 130)
{
break;
} else {
cout << "This temperature is not valid\n";
cout << "Please enter a temperature between -50 and 130 degrees F \n";
cout << "Please enter a new temperature: ";
}
}
}
}
void WeatherStation::DisplayATemperatures( int atemps[], int aTemps)
{
cout << setw (5) << "Hour" << setw(24)<< "Temperature \n";
cout << "\n";
for (int k = 0; k < aTemps; k++)
{
cout << setw (3) << k << ":00" << setw (16) << atemps[k]<<endl;
}
cout <<"\n";
}
void WeatherStation::arrayCalcs(int atemps[], int aTemps)
{
int sumA = 0;
double average = 0.0;
int minA = atemps[0];
int maxA = atemps[0];
int lowest = 0;
int highest = 0;
//Sum of the AM temps
for (int kk = 0; kk < aTemps; kk++)
{
sumA = sumA + atemps[kk];
}
//calculation for average
average = sumA / aTemps;
//Figuring out the Min and Max AM temps
for (int MM = 0; MM < aTemps; MM++)
{
if(minA > atemps[MM])
{
minA = atemps[MM];
}
else if(maxA < atemps[MM])
{
maxA = atemps[MM];
}
lowest = minA;
highest = maxA;
}
//Display of the Calculation results
cout << "This is the average of todays temperatures: " << average <<endl;
cout <<endl;
cout << "Todays High temperature is: " << highest <<endl;
cout <<endl;
cout << "Todays Low temperature is: " << lowest <<endl;
}
int main()
{
cout <<"Welcome to the weather station.\n";
cout <<"Please enter Ferenheit temperatures for calculations: \n";
WeatherStation alpha;
alpha.GetATemperatures(atemps, aTemps);
alpha.DisplayATemperatures(temps, Temps);
alpha.arrayCalcs(temps,Temps);
cout << "\n";
system("pause");
return 0;
}
1) Is the array atemps[]? If so, it's already private... what's the problem?
2) Why is your array class member static? Don't do that without damned good reason (and as this appears to be a homework assignment, I'm almost certain you don't have a damned good reason).
3) Your constructor has a useless line of code in it -- and that's the only line in the function.
4) Your professor will not accept you naming variables atemps and aTemps -- and if they do overlook it, I would be very concerned for the quality of education you're receiving. It's not that the variable names themselves are a big issue, but rather that you're naming them so similarly, as this is a recipe for a maintenance nightmare if it were to happen in real code.
Edit -- based on our comment-chat, here is my suggestion. I have not tried to compile this and I don't claim this is the best (or even a suggested) way to write your program... my suggestion is limited to leaving the data within your object (in a way that has room for growth beyond this question / discussion).
#include <iostream>
#include <iomanip>
using namespace std;
class WeatherStation
{
public:
WeatherStation();
void GetATemperatures();
void DisplayATemperatures();
void arrayCalcs();
private:
static const int aTemps = 24;
int atemps[aTemps];
};
WeatherStation::WeatherStation()
{
}
void WeatherStation::GetATemperatures()
{
for (int i = 0; i < aTemps; i++ )
{
cout << "Please enter the temperature for " << i << ":00 ";
while(true)
{
cin >> atemps[i];
if(atemps[i] >= -50 && atemps[i] <= 130)
{
break;
} else {
cout << "This temperature is not valid\n";
cout << "Please enter a temperature between -50 and 130 degrees F \n";
cout << "Please enter a new temperature: ";
}
}
}
}
void WeatherStation::DisplayATemperatures()
{
cout << setw (5) << "Hour" << setw(24)<< "Temperature \n";
cout << "\n";
for (int k = 0; k < aTemps; k++)
{
cout << setw (3) << k << ":00" << setw (16) << atemps[k]<<endl;
}
cout <<"\n";
}
void WeatherStation::arrayCalcs()
{
int sumA = 0;
double average = 0.0;
int minA = atemps[0];
int maxA = atemps[0];
int lowest = 0;
int highest = 0;
//Sum of the AM temps
for (int kk = 0; kk < aTemps; kk++)
{
sumA = sumA + atemps[kk];
}
//calculation for average
average = sumA / aTemps;
//Figuring out the Min and Max AM temps
for (int MM = 0; MM < aTemps; MM++)
{
if(minA > atemps[MM])
{
minA = atemps[MM];
}
else if(maxA < atemps[MM])
{
maxA = atemps[MM];
}
lowest = minA;
highest = maxA;
}
//Display of the Calculation results
cout << "This is the average of todays temperatures: " << average <<endl;
cout <<endl;
cout << "Todays High temperature is: " << highest <<endl;
cout <<endl;
cout << "Todays Low temperature is: " << lowest <<endl;
}
int main()
{
cout <<"Welcome to the weather station.\n";
cout <<"Please enter Ferenheit temperatures for calculations: \n";
WeatherStation alpha;
alpha.GetATemperatures();
alpha.DisplayATemperatures();
alpha.arrayCalcs();
cout << "\n";
system("pause");
return 0;
}