这是我需要解决的程序:
编写一个程序,要求用户输入10个不同的人(
Person 1, Person 2, ..., Person 10
)吃早餐的煎饼数量。
一旦输入数据,程序必须分析数据并输出哪个人吃早餐最煎饼。
是否有人可以编写返回最大值索引的代码(我将其标记为“h”)
#include "iostream"
using namespace std;
int main()
{
int x[11];
int y;
int h;
for (int i = 1; i <= 10; i++)
{
cin >> i[x];
cout << "Person: " << i << " has eaten " << i[x] << " pancakes" << endl
y = x[0];
h = x[0];
for (int j = 1; j <= 10; j++)
{
if (x[j] > y)
{
y = x[j];
}
}
}
cout << "The most pancakes are eaten by Person " << h << " with " << y << endl;
system("pause");
return 0;
}
答案 0 :(得分:0)
未经测试,应该有效:
#include <iostream>
using namespace std;
int main()
{
int x[11];
int ans, ansmax = 0;
for (int i = 1; i <= 10; i++)
{
cin >> x[i]; // You had wrong variable here
cout << "Person: " << i << " has eaten " << x[i] << " pancakes" << endl
if(x[i] > ansmax)
{
ansmax = x[i];
ans = i;
}
}
cout << "The most pancakes are eaten by Person " << ans << " with " << ansmax << endl;
system("pause");
return 0;
}
答案 1 :(得分:0)
我的五美分
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
const int N = 10;
int person[N];
// Entering initial data
for ( int i = 0; i < N; i++ )
{
cout << "Enter number of pancakes eaten by person " << i + 1 << ": ";
cin >> person[i];
}
// Finding the index (favorite) of the person who has eaten the most pancakes.
int favorite = 0;
for ( int i = 1; i < N; i++ )
{
if ( person[favorite] < person[i] ) favorite = i;
}
// Now all is ready to show the result
cout << "\nThe most pancakes are eaten by Person " << favorite + 1
<< " with " << person[favorite] << endl;
system( "pause" );
return 0;
}
答案 2 :(得分:0)
#include <algorithm>
int index = std::max_element(x, x + 11) - x;