我应该在数组中找到最小值和最大值,但我似乎无法弄清楚为什么答案不正确。例如,如果我输入“1 2 3 4 5”作为我的五次,它告诉我1是我的最大值,0是最小值。出于某种原因,无论第一个数字是多少,它都会将其称为最大值,并将最小值指定为0。查找五次数组中的最大值和最小值
#include <iostream>
using namespace std;
int find_distance(int j); //a function that returns a distance based on the choice j
int intmax, intmin;
int main()
{
int i =0;
int distance[6];
double data[6][5];
for(int j = 0; j < 6; j++)
{
distance[j] = find_distance(j);
cout << "\nEnter 5 of your best running times for \n " << distance[j] << " m \n";
for(int i = 0; i < 5; i++)
{
cout << "Enter a time \n"; cin >> data[j][i];
}
}
cout << "Here is your best 5 times: ";
for(int j = 0; j < 6; j++)
{
cout << "\nDistance : " << distance[j] << " m \n";
for(int i = 0; i < 5; i++)
{
system ("pause");
cout << data[j][i] << "\t"; } cout << endl;
if (data[j][i] < intmin)
intmin = data[j][i];
else if (data[j][i] > intmax)
intmax = data[j][i];
cout << "The maximum time is: " << intmax << endl;
cout << "The minimum time is: "<< intmin << endl;
}
return 0;
}
int find_distance(int j)
{
switch (j)
{ case 0: // 100 meter
return 100;
break;
case 1: // 150 meter
return 150;
break;
case 2: // 200 meter
return 200;
break;
case 3: // 400 meter
return 400;
break;
case 4: // 500 meter
return 800;
break;
default: // 1600 meter
return 1600;
}
}
你为什么不排序值并找到第一个和最后一个元素? – nitinsh99
@ nitinsh99因为这会使它O(log n)而不是O(n)?可能在很短阵列的情况下,这并不重要,但是我在这里感觉到了作业,并且可能OP应该提供比给定的更通用的解决方案。 – 2013-11-01 07:16:34
[在数组中找到最大和最小数字]的可能重复(http://stackoverflow.com/questions/16298906/find-largest-and-smallest-number-in-an-array) – Torben