我正在为学校做编程工作, (只需要帮助我原始代码的一部分,而不是作业解决者,谢谢。) 和我的函数,findHighest()不能正常工作。而不是存储传递给它的double值的数组,我相信它只有零。 我需要帮助解决这个问题。 感谢
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;
}
答案 0 :(得分:1)
尝试以下
#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;
}
或者你可以写
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;
}
使用数组的其他解决方案
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;
}
第一个和第三个解决方案基于C ++ 2011的功能。但是在第三个解决方案中,您可以简单地将基于for语句的范围替换为普通for循环。这是你的任务。:)