如何输出输入到数组中的最小值? (C ++)

时间:2017-10-16 23:09:52

标签: c++ arrays

如何在数组中找到最小值?我认为我做得对,但是当我运行程序时它输出零。

我在另一个程序中以相同的方式完成它并且它有效。运行时,显示最高元素,但最低显示为零。

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    const int ARRAY_SIZE = 12;
    double rainfall[ARRAY_SIZE];
    double total_year, monthly_average;
    double highest = rainfall[0];
    double lowest = rainfall[0];

    cout << " Input rainfall for each month: \n" ;

    for(int index = 0; index < ARRAY_SIZE; index++)
    {
        cout << " Month " << index+1 << ": " ;
        cin >> rainfall[index];
        total_year += rainfall[index];

        if(rainfall[index] < 0)
        {
            cout << " Rainfall must equal to 0 or higher: " ;
            cin >> rainfall[index];
        }
    }
    for(int x = 0; x < ARRAY_SIZE; x++)
    {
        if(highest < rainfall[x])
        {
            highest = rainfall[x];  
        }
        if(lowest > rainfall[x])
        {
            lowest = rainfall[x];
        }
    }
    cout << fixed << setprecision(2) << endl;

    cout << " There was " << total_year << " inches" ;
    cout <<  " of rainfall this year. \n" ; 

    cout << " The monthtly average was " << total_year / 12 ;
    cout << " inches of rainfall.\n";   

    cout << " The highest rainfall was " << highest << " inches" << endl;
    cout << " The lowest rainfall was " << lowest << " inches" << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

尝试声明变量的使用位置。否则代码将不太可读。

阵列降雨尚未初始化

double rainfall[ARRAY_SIZE];
//...
double highest = rainfall[0];
double lowest = rainfall[0];

因此,对变量highestlowest使用具有不确定值的元素是没有意义的。

在计算它们的循环之前声明并初始化变量。

double highest = rainfall[0];
double lowest = rainfall[0];

for(int x = 0; x < ARRAY_SIZE; x++)
{
    if(highest < rainfall[x])
    {
        highest = rainfall[x];  
    }
    if(lowest > rainfall[x])
    {
        lowest = rainfall[x];
    }
}

在这个循环中

for(int index = 0; index < ARRAY_SIZE; index++)
{
    cout << " Month " << index+1 << ": " ;
    cin >> rainfall[index];
    total_year += rainfall[index];

    if(rainfall[index] < 0)
    {
        cout << " Rainfall must equal to 0 or higher: " ;
        cin >> rainfall[index];
    }
}

移动声明

    total_year += rainfall[index];
在if语句之后

for(int index = 0; index < ARRAY_SIZE; index++)
{
    cout << " Month " << index+1 << ": " ;
    cin >> rainfall[index];

    if(rainfall[index] < 0)
    {
        cout << " Rainfall must equal to 0 or higher: " ;
        cin >> rainfall[index];
    }

    total_year += rainfall[index];
}

我会将if语句替换为像

这样的while语句
    while (rainfall[index] < 0)
    {
        cout << " Rainfall must equal to 0 or higher: " ;
        cin >> rainfall[index];
    }

但在使用变量total_year之前,您必须初始化它

double total_year = 0.0;

代码中未使用变量monthly_average。所以它的声明可以删除。

考虑到C ++ std::min_elementstd::max_elementstd::minmax_element中有以下算法可用于查找数组或其他容器中的最小和最大量。