Im working on a programming assignment for school, (Simply need help with a part of my original code, not a homework solver, thanks.) and my function, findHighest() is not working appropriately. Instead of the array storing the double values being passed to it, i believe it just has zeros. I need help remedying this. Thanks
int main()
{
double nEast = 0, sEast = 0, nWest = 0, sWest = 0;
cout << "\n\n\t\tQuarterly Sales Report by region\n";
cout << "\n\nNorth East region:\n" ;
nEast = getSales(nEast);
cout << "\n\nSouth East region:\n";
sEast = getSales(sEast);
cout << "\n\nNorth West region:\n";
nWest = getSales(nWest);
cout << "\n\nSouth West region:\n";
sWest = getSales(sWest);
findHighest(nEast, sEast, nWest, sWest);
return 0;
}
void findHighest (double nEast, double sEast, double nWest, double sWest)
{
double regions[4] = {nEast, sEast, nWest, sWest};
double temp = 0;
for(int i = 0; i <= 3;)
{
if(regions[i] >= temp)
{
temp = regions[i];
cout << temp;
i++;
}
}
cout << "The biggest number is: " << temp << endl;
}
1 Answer 1
Try the following
#include <algorithm>
//...
void findHighest( double nEast, double sEast, double nWest, double sWest )
{
std::cout << "The biggest number is: "
<< std::max( { nEast, sEast, nWest, sWest } ) << std::endl;
}
Or you can write
void findHighest( double nEast, double sEast, double nWest, double sWest )
{
double max = nEast;
if ( max < sEast ) max = sEast;
if ( max < nWest ) max = nWest;
if ( nax < sWest ) max = sWest;
std::cout << "The biggest number is: "
<< max << std::endl;
}
Or another solution using an array
void findHighest( double nEast, double sEast, double nWest, double sWest )
{
double regions[] = { nEast, sEast, nWest, sWest };
double max = regions[0];
for ( double x : regions )
{
if ( max < x ) max = x;
}
std::cout << "The biggest number is: "
<< max << std::endl;
}
The first and the third solutions are based on features of the C++ 2011. However in the third solution you can simply substitute the range based for statement for ordinary for loop. It is your assignment.:)
iin a weird place?findHighest, the variables are set to what you expect them to be?iwere not incremented, the loop would not terminate.iloop is infinite if the regions are not sorted in ascending order alreadyforloop does not automatically increment the counter. Indeed,foradds no functionality awhileloop could not do.