返回具有最高值的数组的名称 刚开始学习C++几周,一直在练习。尽管我一直在尝试返回数组中包含最高数字的数组名。例如,我为10个人制作了一个数组,让每个人输入他们吃的煎饼数量,现在我想返回吃煎饼最多的人。只是不知道怎么做。它在第二个if语句中崩溃 int main() { int pancakes[9] = {0,0,0,0,0,0,0,0,0}; int max = pancakes[0]; int i; int p; for (int x=0; x<=9; x++) { cout << "Enter number " << endl; cin >> i; pancakes[x] = i; if(i > max) max = i; pancakes[x] = p; } cout << endl; cout << p << " ate the most pcakes @ " << max << endl; return 0; } intmain() { int pancakes[9]={0,0,0,0,0,0,0}; int max=煎饼[0]; int i; INTP; 对于(整数x=0;x最大值) max=i; 煎饼[x]=p; } cout

返回具有最高值的数组的名称 刚开始学习C++几周,一直在练习。尽管我一直在尝试返回数组中包含最高数字的数组名。例如,我为10个人制作了一个数组,让每个人输入他们吃的煎饼数量,现在我想返回吃煎饼最多的人。只是不知道怎么做。它在第二个if语句中崩溃 int main() { int pancakes[9] = {0,0,0,0,0,0,0,0,0}; int max = pancakes[0]; int i; int p; for (int x=0; x<=9; x++) { cout << "Enter number " << endl; cin >> i; pancakes[x] = i; if(i > max) max = i; pancakes[x] = p; } cout << endl; cout << p << " ate the most pcakes @ " << max << endl; return 0; } intmain() { int pancakes[9]={0,0,0,0,0,0,0}; int max=煎饼[0]; int i; INTP; 对于(整数x=0;x最大值) max=i; 煎饼[x]=p; } cout,c++,arrays,C++,Arrays,循环和if语句应如下所示。请参见备注中的详细信息和说明: for (int x=0; x<9; x++) // You need to exclude 9 (do not use <=) because the index start at 0 { cout << "Enter number " << endl; cin >> i; //pancakes[x] = i; <-- This line and the arra

循环和if语句应如下所示。请参见备注中的详细信息和说明:

for (int x=0; x<9; x++) // You need to exclude 9 (do not use <=) because the index start at 0
{
   cout << "Enter number " << endl;
   cin >>  i;
   //pancakes[x] = i; <-- This line and the array is not needed. With this also you actually don't need to 
   //                     store/save what people enter. You just need to keep the max and index

    if(i > max)  // if i (number entered) is bigger than the current max of pancakes
    {
        max = i; // You update the max to the new number entered (i)
        p = x + 1; // you store in p the array index + 1 (your array index start at 0 not 1) 
                   // of the current person who eat the max number of pancakes
    }
}
对于(intx=0;x一些事情:

1) 你的迭代是错误的。应该是:

for (int x = 0; x < 9; ++x)
for(int x=0;x<9;++x)

如果您使用x我正在使用手机,因此如果出现格式问题,我深表歉意

你说你的代码在第二个if语句中崩溃了,但是只有一个if语句,所以我假设它是if语句中的第二行。然而,这有两个问题

  • 您没有用以下内容正确记录此人: 煎饼[x]=p 这“应该是”: p=x

  • 您需要在整个语句周围加上大括号。例如:

    如果(i>max){ max=i; p=x; }


  • if(i>max)
    行下的代码周围缺少一些大括号。另外,我认为你想要
    p=x
    而不是
    pancakes[x]=p
    。你想要
    p
    代表什么?是的,我知道带if的大括号,但仍然不适用于它们。。。但是我想用p来表示一个数组,这个数组包含吃了最多煎饼的人。所以,如果第五个人是煎饼[5],他吃了100个煎饼。我想让p代表煎饼[5],而不是它所包含的元素。这是我正在做的练习,让你们更好地了解我想要实现的目标。编写一个程序,要求用户输入10个不同的人(1人,2人,…,10人)早餐吃的煎饼数量一旦输入数据,程序必须分析数据并输出哪个人早餐吃的煎饼最多。但是,您的变量
    max
    已经表示最大煎饼值。仍然有点困惑。。所以没有办法输出,比如说煎饼[5]吃了最多的煎饼,我只能保存煎饼[5]的值并输出它?据我所知,p只包含x的值,这不是真正的煎饼[5],我想我只需要读几遍你的帖子。谢谢你们的快速回复,你们太棒了@MarkCastilla如果pancake[5]是最大值,并且在发现时设置p=x(即,在更新max的If语句中),则p=5。当你去打印谁吃得最多时,你能做的就是:我现在能看到吗。我试图让它自己输出pancake[5],就像cout一样。如果以后在程序中需要检索/显示/修改每个用户的数据,那么您的表可能会很有用。但对于这个简单的问题,也没有必要。如果这对你有帮助,请接受答案。谢谢:)@MarkCastilla如果答案对你有帮助,请毫不犹豫地接受。谢谢:)
    for (int x = 0; x < 9; ++x)