以下代码未对Stdout做出任何回应

时间:2017-09-12 14:55:08

标签: c++ arrays

此代码应该计算数组中最大数字的频率I.E数组中出现最大数字的次数,但遗憾的是,此代码不显示任何输出: -

#include<iostream>
#include <bits/stdc++.h>

using namespace std;

int birthdayCakeCandles(int n, int a[]){
int j=0,max,count=0;
max = a[j];
while(j<n){
if(a[j+1]> max){
    max = a[j+1];
    j++;
}

}
int seen[n];
for(int i = 0; i < n; i++)
    seen[i] = 0; 

for(int i = 0; i < n;i++) {
    if(seen[i] == 0) {
        int count = 0;
        for(int j = i; j < n;j++)
            if(a[j] == a[i] && a[i] == max)
                count += 1;
                seen[j] = 1;

    }
    }
return count;
} 

int main() {
int i,n;
cin >> n;
int a[n];
for(i = 0; i < n; i++){
   cin >> a[i];
}
int result = birthdayCakeCandles(n, a);
cout << result << endl;
return 0;
}

2 个答案:

答案 0 :(得分:1)

你的程序永远不会停止,因为你的最大发现循环是n > 0无穷无尽的。您在birthdayCakeCandles中的循环应更改为:

while (j < n)
{
    if (a[j + 1] > max)
    {
        max = a[j + 1];
    }

    j++;
}

另请考虑使用更易读的编码风格,请阅读this

答案 1 :(得分:1)

除了vasek发现的错误之外,你在(过于复杂的)跟随循环中至少犯了另一个错误,在那里你试图计算最大值的出现次数。

git checkout <old_commit>
git review

一旦找到最大值,您需要做的就是:

// I've kept OP's indentation on purpose... 
int seen[n];                 // <-- Variable Length Arrays are not standard in C++
for(int i = 0; i < n; i++)
    seen[i] = 0; 

for(int i = 0; i < n;i++) {
    if(seen[i] == 0) {
        int count = 0;
        for(int j = i; j < n;j++)
            if(a[j] == a[i] && a[i] == max)
                count += 1;
                seen[j] = 1;   // <-- misleading indentation, this is always executed
                               // no matter what the condition is 
    }
    }

事实上(除非你想出于其他原因创建一个在数组上运行的函数),你根本不需要任何数组(或std :: vector)来完成你的任务。此代码将执行相同的任务:

int count = 0;
for( int i = 0; i < n; ++i ) {
    if( a[i] == max )
        ++count;
}