I need to display the highest and lowest sales values - c++

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.

Related

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.

C++ - Passing an Array of Structure Type to a User Defined Function

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();
}

How to print 3 different values per line in C++

My program reads 366 lines of data from a file, each line has 2 values; minimum temperature and maximum temperature. I want to output when there were three consecutive days where the temperature went above a certain number n, that the user enters.
This is what I have:
cout<<"Please enter a number to search: ";
cin>>n;
out<<endl;
out<<"Occasions during the year when there were three consecutive days
where the temperature went above "<<n<<" are:"<<endl;
out<<"Days: ";
for(int x=0; x<366; x=x+1){
in>>minimum[x];
in>>maximum[x];
if(minimum[x]>n){
day1=x;
}
if(maximum[x]>n){
day1=x;
}
out<<"Days: "<<day1<<", "<<day2<<", "<<day3<<endl;
}
}
I'm having trouble understanding how to update day 2 and day 3 to a different element of the array that satisfies the condition. When the condition is met, I want to store the days and print them like:
Occasions during the year (if any) when there were three consecutive days where the temperature went above 34 are:
Days:103, 104, 105
Days:107, 108, 109
Days:288, 289, 290
the days are the locations in the array.
Try something more like this:
cout << "Please enter a number to search: ";
cin >> n;
out << endl;
out << "Occasions during the year when there were three consecutive days where the temperature went above " << n << " are:" << endl;
int firstday, numdays = 0;
for (int x = 0; x < 366; ++x)
{
in >> minimum[x];
in >> maximum[x];
if (maximum[x] > n)
{
++numdays;
if (numdays == 1)
firstday = x;
else if (numdays == 3)
{
out << "Days: " << firstday << ", " << firstday+1 << ", " << firstday+2 << endl;
numdays = 0;
}
}
else
numdays = 0;
}
Alternatively:
cout << "Please enter a number to search: ";
cin >> n;
out << endl;
out << "Occasions during the year when there were three consecutive days where the temperature went above " << n << " are:" << endl;
for (int x = 0; x < 366; ++x)
{
in >> minimum[x];
in >> maximum[x];
}
for (int x = 0; x < 366-2; ++x)
{
if (maximum[x] > n)
{
int firstday = x;
int numdays = 1;
for (int y = 1; y < 3; ++y)
{
if (maximum[x+y] > n)
++numdays;
else
break;
}
if (numdays == 3)
out << "Days: " << firstday << ", " << firstday+1 << ", " << firstday+2 << endl;
x += (numdays-1);
}
}
I suggest you break this down into smaller parts. For example, you could do this in two broad steps:
Read in all the data
Find all sets of 3 days which are above the given temperature
By doing each of these separately, you can focus on one piece at a time, rather than trying to do both.
Note, that you only need if(maximum[x] > n).
Create an int variable to act as a flag. Every time you get a 'good' day, add 1 to that flag and subtract 1 if not. So, in the end, just add an if statement that checks if that flag variable is three, and then print the value.
Hope this helps!

Arrays and min values

Currently working on a project where I have two arrays (one 1-D and another 2-D). One contains names and another contains a set of numbers. I'm working on a function that finds the lowest value in the table and outputs it. However, I need to attribute the name of the monkey to the amount of food he has eaten. So "Monkey 1 has eaten the least amount of food only eating 11 pounds on Day 1". Below is the function to find the lowest value which is working fine, however I'm not sure how to implement the monkey's name (without just typing it in) and the day of the week. If the rest of my code is needed please let me know.
void leastAmt(string names[], int food[][NUM_DAYS])
{
int lowest = food[0][0];
for (int monkey = 0; monkey < NUM_MONKEYS; monkey++)
{
for (int day = 0; day < NUM_DAYS; day++)
{
if (food[monkey][day] < lowest)
lowest = food[monkey][day];
}
}
cout << "Least amount of food: " << lowest << endl;
}
create two variables for storing monkey and money values.
int lowest_monkey, least_day;
Whenever lowest value is modified update these values with current values of monkey and day variables.
Replace the last line with the following
cout << "Monkey " << lowest_monkey << " has eaten least amount of food only eating " << lowest << " on " << least_day << endl;
Store least_eating_monkey in an array, storing monkey names for each day.
int leastEatingMonkey[NUM_DAYS];
for (int day = 0; day < NUM_DAYS; day++)
{
lowest = INT_MAX;
for (int monkey = 0; monkey < NUM_MONKEYS; monkey++)
{
if (food[monkey][day] < lowest){
leastEatingMonkey[day] = monkey;
lowest = food[monkey][day];
}
}
}
for (int day = 0; day < NUM_DAYS; day++)
{
cout << "monkey " << names[day] << " ate least amount of food on day " << day << endl;
}

Function not returning the highest and lowest values entered into the array

This function is not accurately returning the highest and lowest values entered into the array. I'm not sure what I code I entered for the program to do this. This program needs to return the average of all of the elements entered into the array (the average part works fine) as well as find the highest and lowest values among all of the values entered into the array. Please help!
#include <iostream>
using namespace std;
float temptotal = 0;
float averagetemp = 0;
float temperatures[50];
float average(int);
void highest(int);
void lowest(int);
int main()
{
int days = 0;
cout << "Enter the number of days: ";
cin >> days;
if (days > 50)
{
cout << "You may only enter temperatures for 50 days." << endl;
return 0;
}
average(days);
highest(days);
lowest(days);
}
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
}
averagetemp = temptotal / days;
cout << "The average temperature is: " << averagetemp << endl;
return averagetemp;
}
void highest(int days)
{
int count;
int highest;
highest = temperatures[50];
for (count = 1; count < days; count++)
{
if (temperatures[count] > highest)
highest = temperatures[count];
cout << "The highest temperature is: " << highest << endl;
}
}
void lowest(int days)
{
int count;
int lowest;
lowest = temperatures[50];
for (count = 1; count < days; count++)
{
if (temperatures[count] < lowest)
lowest = temperatures[count];
cout << "The lowest temperature is: " << lowest << endl;
}
}
This function
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
//...
is already wrong because element temperatures[0] will not be uninitialized. You have to write
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i-1];
temptotal += temperatures[i-1];
//...
Or
float average(int days)
{
for (int i = 0; i < days; i++)
{
cout << "Enter the temperature for day number " << i + 1 << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
//...
Functions highest and lowest are also wrong. For example array temperatures has no element with index 50. Moreover the user can enter number of days less than 50. So this statement
highest = temperatures[50];
is wrong.
The functions can be written like this function definition
void highest( int days )
{
int highest = temperatures[0];
for ( int count = 1; count < days; count++ )
{
if ( highest < temperatures[count] ) highest = temperatures[count];
}
cout << "The highest temperature is: " << highest << endl;
}
Take into acccount that there are standard algorithms std::max_element, std::min_element, std::minmax_element declared in header <algorithm> that can be used instead of your functions.
For example function highest can be defined with using standard algorithm std::max_element the following way
#include <algorithm>
//...
void highest( int days )
{
cout << "The highest temperature is: "
<< *std::max_element( temperatures, temperatures + days )
<< endl;
}
Array indices start with a 0
Place the cout statements outside the for loop.
Arrays are indexed from 0 to n-1, where n is the total number of entries in the array. You started the count at 1 in your loop when you should start at 0. If the user entered 50 values, you would have had an out-of-bounds access.
The correction should be:
for (int i = 0; i < days; i++)
Then in your output statement, it should be:
cout << "Enter the temperature for day number " << i+1 << ": ";
The other issue is your highest function. The issue are a few things:
You declared the local variable highest as an int. It should be a float to match the type used in the temperature array.
You should set highest to a very small value, smaller than any you would expect. Or better yet, set it to the first temperature entry before the loop, and start the loop from the second entry.
You named your local variable highest, but your function name is also highest. This will lead to confusion when someone else looks at your code.
If you're interested in another solution, the following computes the highest:
#include <algorithm>
//...
void highest(int days)
{
float theHighest = *std::max_element(temperatures, temperatures + days);
cout << "The highest temperature is: " << theHighest << endl;
}
A little better version from the function 'highest':
void highest(int days)
{
if (days < 1)
{
cout << "No temperatures" << endl;
}
double highest = temperatures[0];
for (int count = 1; count < days; count++)
{
if (temperatures[count] > highest)
{
highest = temperatures[count];
}
}
cout << "The highest temperature is: " << temperatures[highest_index] << endl;
}
All arrays in C++ starting with index 0. In this implementation this point is considered by using the first element (index 0) as thie first highest value. After that the loop has only to deal with the rest, begining at index 1.
The variable 'highest' must be from the type double. Otherwise you may get wrong results, because the highest is a little lower than the real highest due to generaly rounding down (double to int). The next comparison may be assigned even if it is a little lower.
Array indices start with 0 but your loops start at 1. For your loop over days, for instance, this will iterate over the full range:
for (int i = 0; i < days; i++)