求最大值及其下标c++
时间: 2023-11-24 20:50:26 浏览: 231
以下是两种C++求最大值及其下标的例子:
1.使用for循环遍历数组,找到最大值及其下标
```c++
#include <iostream>
using namespace std;
int main() {
int n, a[100];
cin >> n;
for(int i=0; i<n; i++) {
cin >> a[i];
}
int max = a[0]; //最后一个测试点当n最小时
int count = 0;
for(int i=1; i<n; i++) {
if(max < a[i]) {
max = a[i];
count = i;
}
}
cout << max << " " << count;
return 0;
}
```
2.使用for循环遍历数组,找到最大值及其下标,使用if语句判断是否有多个最大值
```c++
#include <iostream>
using namespace std;
int main() {
int n, a[11];
cin >> n;
for(int i=0; i<n; i++) {
cin >> a[i];
}
int max = a[0];
int k = 0;
for(int j=0; j<n; j++) {
if(a[0] < a[j]) {
a[0] = a[j];
k = j;
} else if(a[0] == a[j]) {
if(k > j) {
k = j;
}
}
}
cout << a[0] << " " << k << endl;
return 0;
}
```
阅读全文
相关推荐















