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.
Related
I am doing a a problem using Multi-dimensional Arrays. I call the function in main but I get this Error message. This is the Original Problem I have:
A local zoo wants to keep track of how many pounds of food each of its three tigers eats each day during
a typical week. Write a program that stores this information in a two-dimensional 3 x 7 array, where
each row represents a different tiger and each column represents a different day of the week. The
program should first have the user input the data for each tiger. Then it should create a report that
includes the following information:
Average amount of food eaten by each of the tigers during the week.
Average amount of food eaten by all the tigers per day for each day.
The least amount of food eaten during the week by any tiger.
The greatest amount of food eaten during the week by any tiger.
the code:
#include <iostream>
using namespace std;
const int TIGERS = 3;
const int DAYS = 7;
int food[TIGERS][DAYS];
void inputArray(int food[TIGERS][DAYS]);
float AvgTig(float);
float Least(float);
float most(float);
int main()
{
float maximum;
float minimum;
float total = 0.0f;
float average = 0.0f;
float result = 0;
inputArray(food);
maximum = food[0][0];
minimum = food[0][0];
cout << "\n \n";
AvgTig(result);
cout << "\n \n";
Least(minimum);
cout << "\n \n";
most(maximum);
cout << "\n \n";
system("PAUSE");
return 0;
//end program
}
void inputArray(int food[TIGERS][DAYS])
{
int total = 0;
for (int tig = 0; tig < TIGERS; tig++) {
for (int day = 0; day < DAYS; day++) {
cout << "TIGER " << (day + 1) << ", day " << (day + 1) << ": ";
cin >> food[tig][day];
}
cout << endl;
}
}
float AvgTig(float output)
{
int total = 0;
for (int i = 0; i < TIGERS; i++) {
for (int day = 0; day < DAYS; day++) {
total += food[i][day];
}
cout << endl;
}
output = total / (TIGERS * DAYS);
cout << "Average food for Tigers in the days is :" << output << " ";
return output;
}
float Least(float minimum)
{
for (int least = 0; least < TIGERS; least++) {
for (int day = 0; day < DAYS; day++) {
if (food[least][day] < minimum)
minimum = food[least][day];
}
}
cout << "Minimum food eaten: " << minimum << " ";
return minimum;
}
float most(float maximum)
{
for (int most = 0; most < TIGERS; most++) {
for (int day = 0; day < DAYS; day++) {
if (food[most][day] > maximum)
maximum = food[most][day];
}
}
cout << " Maximum number of food is: " << maximum << " ";
return maximum;
}
On this line:
inputArray(food[TIGERS][DAYS]);
in main, you are calling inputArray with a single int, and not the entire food array. In fact, even reading this position in food is UB.
You need to call the function like this:
inputArray(food);
I'm completely new to Stack OverFlow so excuse me if I'm breaking any rules or incorrectly asking a question (I would also appreciate advice on how to properly ask questions on Stack overflow).
Anyways so I get this error
*"argument of type 'data *' is incompatible with parameter of type 'data '."
when I call the user-defined function weather in int main(). I would appreciate it if someone could take a look at my code and guide me to what's causing the error. Just so you know, I am currently taking a programming fundamentals intro course and I have not learned about classes and pointers yet.
Thanks!
#include <iostream>
#include <string>
using namespace std;
const int SIZE = 2;
void weather(struct data array[], int SIZE, string months[]);
int main()
{
string months[12] = { "January", "February", "March", "April", "May", "June"
"July", "August", "September", "October", "November", "December" };
struct data {
double totalRainfall;
double highTemp;
double lowTemp;
double avgTemp;
};
data annualWeather[SIZE];
//Asks user for total rainfall, high and low temperature, and calculates
//avg temperature of each month
for (int i = 0; i < SIZE; i++)
{
cout << "What was the total rainfall in " << months[i]
<< "?" << endl;
cin >> annualWeather[i].totalRainfall;
//Prompts user for temperature high
do
{
cout << "What was the temperature high in " << months[i]
<< "?" << endl;
cin >> annualWeather[i].highTemp;
} while (annualWeather[i].highTemp > 140);
//Prompts user for temperature low
do
{
cout << "What was the temperature low in " << months[i]
<< "?" << endl;
cin >> annualWeather[i].lowTemp;
} while (annualWeather[i].lowTemp < -100);
annualWeather[i].avgTemp = (annualWeather[i].highTemp + annualWeather[i].lowTemp) / 2;
}
**weather(annualWeather, SIZE, months); <--THIS IS WHERE I SEE ERROR**
return 0;
}
void weather(struct data array[], int SIZE, string months[])
{
double avgRainFall = 0;
double totalAnnualRainFall = 0;
double annualHigh = 0;
double annualLow = 0;
double avgMonthlyTemp = 0;
//Calculates sum annual rain fall, total annual rain fall, and total average monthly temperature
for (int i = 0; i < SIZE; i++)
{
avgRainFall += annualWeather[i].totalRainfall;
totalAnnualRainFall += annualWeather[i].totalRainfall;
avgMonthlyTemp += annualWeather[i].avgTemp;
}
//Calculates average annual rain fall and average annual monthly temperature
avgRainFall = avgRainFall / SIZE;
avgMonthlyTemp = avgMonthlyTemp / SIZE;
//Selection Sort of annualWeather[].highTemp
for (int index = 0; index < SIZE - 1; index++)
{
//Find location of smallest element
int smallestIndex = index;
for (int location = index + 1; location < SIZE; location++)
if (annualWeather[location].highTemp < annualWeather[smallestIndex].highTemp)
smallestIndex = location;
//Swap smallest element of annualWeather[].highTemp to front
int tempSales = annualWeather[smallestIndex].highTemp;
annualWeather[smallestIndex].highTemp = annualWeather[index].highTemp;
annualWeather[index].highTemp = tempSales;
//Swap smallest element of months[] to front
string tempMonths = months[smallestIndex];
months[smallestIndex] = months[index];
months[index] = tempMonths;
}
//Displays average monthly rainfall, total annual rainfall, annual high, annual low,
//And average of the monthly temperature averages
cout << "The average monthly rainfall is " << avgRainFall << "." << endl
<< "The total rainfall for the year is " << totalAnnualRainFall << "."
<< endl << "The high temperature of the year is " << annualHigh << " during "
<< months[0] << endl << "The low temperature of the year is " << annualLow << " during "
<< months[2] << endl << "The average temperature of all the monthly averages is "
<< avgMonthlyTemp << ".";
cin.get(); cin.get();
}
The struct data declared in your main function is different from the struct data used in the prototype of your weather function.
Move the definition of struct data out of main to the global namespace, somewhere before you use it to declare weather.
For the first please specified your personal data types in global space.
Your problem not in sending array to function. Problem inside your function
you send array to them with name array, and inside trying to access them by name from main. Just rename your function parameter.
void weather(Data array[], int SIZE, string months[])
{
double avgRainFall = 0;
double totalAnnualRainFall = 0;
double annualHigh = 0;
double annualLow = 0;
double avgMonthlyTemp = 0;
//Calculates sum annual rain fall, total annual rain fall, and total average monthly temperature
for (int i = 0; i < SIZE; i++)
{
avgRainFall += array[i].totalRainfall;
totalAnnualRainFall += array[i].totalRainfall;
avgMonthlyTemp += array[i].avgTemp;
}
//Calculates average annual rain fall and average annual monthly temperature
avgRainFall = avgRainFall / SIZE;
avgMonthlyTemp = avgMonthlyTemp / SIZE;
//Selection Sort of annualWeather[].highTemp
for (int index = 0; index < SIZE - 1; index++)
{
//Find location of smallest element
int smallestIndex = index;
for (int location = index + 1; location < SIZE; location++)
if (array[location].highTemp < array[smallestIndex].highTemp)
smallestIndex = location;
//Swap smallest element of annualWeather[].highTemp to front
int tempSales = array[smallestIndex].highTemp;
array[smallestIndex].highTemp = array[index].highTemp;
array[index].highTemp = tempSales;
//Swap smallest element of months[] to front
string tempMonths = months[smallestIndex];
months[smallestIndex] = months[index];
months[index] = tempMonths;
}
//Displays average monthly rainfall, total annual rainfall, annual high, annual low,
//And average of the monthly temperature averages
cout << "The average monthly rainfall is " << avgRainFall << "." << endl
<< "The total rainfall for the year is " << totalAnnualRainFall << "."
<< endl << "The high temperature of the year is " << annualHigh << " during "
<< months[0] << endl << "The low temperature of the year is " << annualLow << " during "
<< months[2] << endl << "The average temperature of all the monthly averages is "
<< avgMonthlyTemp << ".";
cin.get(); cin.get();
}
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!
double gross_pay(double pay[7]){
int i;
double add;
add = 0;
for(i = 0; i < 7; i++){
add += pay[i];
}
return add;
}
int find_lowest(double pay[7]){
double lowest;
int index, i;
index = 0;
lowest = pay[0];
for(i = 1; i < 7; i++){
if(pay[i] < lowest){
index = i;
lowest = pay[i];
}
}
return index;
}
int find_highest(double pay[7]){
double highest;
int index, i;
index = 0;
highest = pay[0];
for(i = 1; i < 7; i++){
if(pay[i] > highest){
index = i;
highest = pay[i];
}
}
return index;
}
int main()
{
string dayweek[7];
double dailypay[7];
int i;
double pay, add;
int lowest, highest;
dayweek[0] = "Monday";
dayweek[1] = "Tuesday";
dayweek[2] = "Wednesday";
dayweek[3] = "Thursday";
dayweek[4] = "Friday";
dayweek[5] = "Saturday";
dayweek[6] = "Sunday";
for(i = 0; i < 7; i++){
cout << "Please enter the gross sales ecieved on" << endl;
cout << dayweek[i] << ": ";
cin >> pay;
dailypay[i] = pay;
cout << endl << endl;
}
add = gross_pay(dailypay);
lowest = find_lowest(dailypay);
highest = find_highest(dailypay);
cout << endl;
cout << "Total sales for the week: " << "$" << add << endl << endl;
cout << "Total taxes withheld: $" << add*.0975 << "\n\n";
cout << "Net profit: $" << add*.9025 <<"\n\n";
cout << "Day with the highest sales amount was" << endl;
cout << dayweek[highest].c_str() <<" with a sales total of $" << dailypay[highest];
cout << "\n\nDay with the lowest sales amount was" << endl;
cout << dayweek[lowest].c_str() << " with a sales total of $" << dailypay[lowest];
return 0;
}
cant seem to figure out the code that will sort the array in order from lowest to highest for example
Sales sorted from lowest to highest:
Monday had gross sales of $101.00
Tuesday had gross sales of $135.64
Sunday had gross sales of $245.55
Wednesday had gross sales of $533.44
Thursday had gross sales of $922.42
Saturday had gross sales of $1555.22
Friday had gross sales of $2242.63
those are also the input values for gross sales,
this is my first time asking a question on this site, if i did anything wrong please let me know,thanks for all the help !
could you write one using this
void sortArray(double arySales[], int size, string aryDays[])
{
bool swap;
double tempSales;
string tempDays;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (arySales[count] > arySales[count + 1])
{
tempSales = arySales[count];
arySales[count] = arySales[count + 1];
arySales[count + 1] = tempSales;
tempDays = aryDays[count];
aryDays[count] = aryDays[count + 1];
aryDays[count + 1] = tempDays;
swap = true;
}
}
} while (swap);
}
You should put the day-of-week index (0 to 6) plus the value for that day into a struct, and then populate a std::vector of these structs. Then you can sort them easily:
struct PayForDay {
int day; // 0..6
double pay;
};
bool PayLess(const PayForDay& lhs, const PayForDay& rhs) {
return lhs.pay < rhs.pay;
}
std::vector<PayForDay> payments;
std::sort(payments.begin(), payments.end(), PayLess);
I need to create a program that enters daily sales for each day of the week. Once the values are entered I need to be able to display:
Sales for day 1 are ###
Sales for day 2 are ###
The lowest sales was XXX
The highest sales was XXX
The problem is that I can't get my code to cout:
Sales for day 1 are XXX
Sales for day 2 are XXX
All I can get it to say is
Sales are:
XXX
XXX
XXX
And I also don't know how to find the lowest and the highest sales. We haven't even begun working with MIN & MAX functions so I'm lost as to how to accomplish it.
My code that I have so far is:
const int DAYS_SALES = 7;
double sales[DAYS_SALES];
int sub;
double min = 0;
double max = 0;
for(sub = 0; sub < DAYS_SALES; ++sub)
{
cout << "Enter in the sales for day " << (sub + 1) << " ";
cin >> sales[sub];
}
cout << endl << "The sales for day are: " << endl;
for (sub = 0; sub < DAYS_SALES; ++sub)
cout << sales[sub] << " " << endl;
Any help would be appreciated!
Track the min and max values as your for loop goes over each value.
If the current value (sales[sub]) is less than the min so far, store that value as the new minimum value.
const int DAYS_SALES = 7;
double sales[DAYS_SALES];
int sub;
double min = 0.0;
double max = 0.0;
for(sub = 0; sub < DAYS_SALES; ++sub)
{
cout << "Enter in the sales for day " << (sub + 1) << " ";
cin >> sales[sub];
}
min = sales[0];
max = sales[0];
cout << endl << "The sales for day are: " << endl;
for (sub = 0; sub < DAYS_SALES; ++sub)
{
cout << endl << "The sales for day are: " << sales[sub] << " " << endl;
if (sales[sub] < min)
{ // If we find a smaller min. value, store that in min
min = sales[sub];
}
if (sales[sub] > max)
{ // If we find a bigger max. value, store that in max
max = sales[sub];
}
}
// Print out the Min and Max that we found.
cout<< "The lowest sales was " << min;
cout<< "The highest sales was " << max <<endl;
Ok, maybe you should enter your values to a std::vector of the appropriate type and then call std::minmax(...) on it.