如何在数组中显示最高值

时间:2014-07-21 21:50:25

标签: c++ arrays

我写的代码有问题。我试图在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;
}

3 个答案:

答案 0 :(得分:3)

问题是比较语句中的额外分号:

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

程序将进行比较sales[i] > highest然后什么都不做......之后它会将销售[i]分配给最高的任何事情。删除那个分号并且它有效。

答案 1 :(得分:0)

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获得的内容存储在数组中?

答案 2 :(得分:0)

您不需要在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;
}