如何显示数组中的最大值

How to display the highest value in an array

本文关键字:数组 最大值 显示 何显示      更新时间:2023-10-16

我写的代码有问题。我试图在void函数中获得数组的最大值,但所有我在编译器中获得的是第4个数组的值,无论其他值如何。所以现在如果我输入40,30,20,10它会将值10赋值为最大值。谁能给我解释一下我到底做错了什么?

#include <iostream>
#include <iomanip>
#include <string>
#include <string.h>
using namespace std;
string divName[4] = { "Northeast", "Southeast", "Northwest", "Southwest" };
double getSales(string name)
{
    double Sales;
    while (1)
    {
        cout << fixed << setprecision(2) << "Enter the quarterly sales for the " << name << " division: ";
        cin >> Sales;
        if (Sales != 0)
            break;
    }
    return Sales;
}
void findHighest(double sales[4])
{
    double highest = 0;
    int division = 0;
    for (int i = 0; i<4; i++)
    {
        if (sales[i] > highest);
        {
            highest = sales[i];
            division = i;
        }
    }
    cout << std::endl;
    cout << fixed << setprecision(2) << "The " << divName[division] << " division had the highest sales this quarter." << std::endl << "Thier sales were $" << highest;
    cout << std::endl;
}
int main()
{
    double sales[4];
    for (int i = 0; i<4; i++)
    {
        sales[i] = getSales(divName[i]);
    }
        findHighest(&sales[0]);
    system("PAUSE");
    return 0;
}

问题是比较语句中多余的分号:

if (sales[i] > highest);  // <<< This semicolon
{
    highest = sales[i];
    division = i;
}

程序将比较sales[i] > highest,然后什么都不做…之后,无论发生什么,它都将sales[i]分配给最高。删除分号就可以了

double getSales(string name)
{
    double Sales;
    while (1)
    {
        cout << fixed << setprecision(2) << "Enter the quarterly sales for the " << name << " division: ";
        cin >> Sales;
        if (Sales != 0)
            break;
    }
    return Sales;
}

这里的代码只将最后一个输入写入Sales。存储你从cin中得到的数组?

不需要在findHighest函数中使用2个变量。它可以只用一个。

void findHighest(double sales[4])
{
    int maxIndex = 0;   
    for (int i = 1; i < 4; i++)
    {
        if (sales[maxIndex] < sales[i])
            maxIndex = i;
    }
    cout << std::endl;
    cout << fixed << setprecision(2) << "The " << divName[maxIndex] << " division had the highest sales this quarter." << std::endl << "Thier sales were $" << maxIndex;
    cout << std::endl;
}