如何显示数组中的最大值
How to display the highest value in an array
我写的代码有问题。我试图在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;
}
相关文章:
- 使用指针从C++中的数组中获取最大值
- 在二维数组中查找最小值和最大值?
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- CUDA - 将 float3 数组的 (x,y,z) 分量的最小值/最大值分开?
- 查找包含 N 个元素的数组的最小值和最大值
- 有没有一种惯用的方法可以在不存储变换或不必要地重新计算的情况下找到数组变换的最小/最大值?
- C++ 从数组中删除一个最大值和零
- 我无法显示包含整数最大值的索引. 但我可以显示数组中整数的最高值
- 使用数组将最后一个最大值更改为第一个最小值
- 练习循环和使用循环 1 次以及如何获取数组的最大值
- 如何在给定数组的任何子数组(任何大小)中找到最大值(或最小值)?
- C++数组的最大值、最小值、平均值函数
- C ++试图找到数组中每一行的最大值
- 从二维数组中查找最小值和最大值
- 数组的最大值
- 数组函数似乎没有找到最大值
- 未初始化数组中的最小值和最大值
- 堆栈或BSS或DATA段上的数组最大大小
- 数的最大值
- 确定strftime字符数组最大大小的智能方法是什么?