C++ 我无法显示包含整数最大值的索引。但我可以显示数组中整数的最大值
我无法显示包含整数最大值的索引。但我可以显示数组中整数的最大值。 这是我的密码:C++ 我无法显示包含整数最大值的索引。但我可以显示数组中整数的最大值,c++,arrays,algorithm,max,C++,Arrays,Algorithm,Max,我无法显示包含整数最大值的索引。但我可以显示数组中整数的最大值。 这是我的密码: #include <iostream> #include<stdlib.h> using namespace std; int main () { int a[10], highest,temp = 0; do{ cout<<"Enter 10 Numbers: "; cin>>a[temp]; t
#include <iostream>
#include<stdlib.h>
using namespace std;
int main () {
int a[10], highest,temp = 0;
do{
cout<<"Enter 10 Numbers: ";
cin>>a[temp];
temp++;
}while(temp !=10);
for(int j = 0; j <10; j++){
if(a[0]<a[j]){
highest = j;
}
}
for(int x = 0; x <10; x++){
if(a[0]<a[x]){
a[0] = a[x];
}
}
cout<<"The highest number is "<<a[0] <<" at index "<<highest<<endl;
system("pause");
return 0;
}
只要将最高值存储在[0]中,就需要将其与新的较大值交换(如果在每次迭代后发现),程序中的一些代码应该如下所示:
for(int j = 0; j <10; j++){
if(a[0]<a[j]){
int tmp = a[0];
a[0] = a[j];
a[j] = tmp;
highest = j;
}
}
一个简单易读的示例如下所示:
int a[10], highest = -1, highestIndex = -1;
for(int i(0); i < 10; i++){
cout<<"a[" << i << "]: ";
cin >> a[i];
}
for(int i = 0; i < 10; i++){
if(a[i] > highest){
highest = a[i];
highestIndex = i;
}
}
cout << "The highest number is " << highest << " at index " << highestIndex << endl;
请不要要求一段时间,你可以处理它
代码的第一部分检测大于第一个元素的元素的最高索引,而不是所有元素中具有最高值的元素的索引:
for(int j = 0; j <10; j++){
if(a[0]<a[j]){
highest = j;
}
}
您可以按如下方式轻松地将两者结合起来。请注意,从1开始即可:
首先,不要在程序中使用幻数,例如数字10。改用命名常量 也在使用变量的最小范围内声明变量 这个环路
for(int j = 0; j <10; j++){
if(a[0]<a[j]){
highest = j;
}
它的输出可能看起来像
Enter 10 umbers: 7 2 3 0 9 1 8 6 4 5
The highest number is 9 at index 4
考虑到报头中声明了标准算法std::max_元素,该算法在序列中查找最大元素并返回指向该元素的迭代器/指针
比如说
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
const size_t N = 10;
int a[N];
std::cout << "Enter " << N << " umbers: ";
for ( size_t i = 0; i < N; i++ ) std::cin >> a[i];
int *max_value = std::max_element( a, a + N );
std::cout << "The highest number is " << *max_value
<< " at index " << std::distance( a, max_value ) << std::endl;
return 0;
}
如果[0]我假设j是我的数组索引。因为它与my array size.tnx具有相同的值,所以有很多匹配项:我想在任何时候都拥有这样的技能:
#include <iostream>
int main()
{
const size_t N = 10;
int a[N];
std::cout << "Enter " << N << " umbers: ";
for ( size_t i = 0; i < N; i++ ) std::cin >> a[i];
size_t max = 0;
for ( size_t i = 1; i < N; i++ )
{
if ( a[max] < a[i] ) max = i;
}
std::cout << "The highest number is " << a[max]
<< " at index " << max << std::endl;
return 0;
}
Enter 10 umbers: 7 2 3 0 9 1 8 6 4 5
The highest number is 9 at index 4
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
const size_t N = 10;
int a[N];
std::cout << "Enter " << N << " umbers: ";
for ( size_t i = 0; i < N; i++ ) std::cin >> a[i];
int *max_value = std::max_element( a, a + N );
std::cout << "The highest number is " << *max_value
<< " at index " << std::distance( a, max_value ) << std::endl;
return 0;
}
Enter 10 umbers: 7 2 3 0 9 1 8 6 4 5
The highest number is 9 at index 4