以下代码不会在Stdout上给出任何响应

The following Code does not give any response on Stdout

本文关键字:任何 响应 Stdout 代码      更新时间:2023-10-16

此代码应该计算数组中最大数字的频率,即不幸的是,数组中最高数字的数量次数不幸的是,此代码没有显示任何输出: -

#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;
}

您的程序永远不会停止,因为您的最大查找循环适用于n > 0。您在birthdayCakeCandles中的循环应更改为:

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

还考虑使用更多可读的编码样式,请阅读此。

除了Vasek发现的错误外,您至少在循环之后(倍增)中犯了另一个错误,您正在尝试计算最大值的出现。

// 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 
    }
    }

当您找到最大值后,您需要做的一切是:

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

事实上(除非您想创建一个在数组上运行的功能),否则您根本不需要任何数组(或std :: vector)即可完成作业。此代码将执行相同的任务:

#include <iostream>
#include <limits>
int main()
{
    int n;
    std::cin >> n;
    int x,
        max = std::numeric_limits<int>::min();
    int count = 0;
    for ( int i = 0;
          i < n  &&  std::cin >> x;
          ++i )
    {
        if ( x >= max )
        {
            if ( x > max )
            {
                max = x;
                count = 1;
            }
            else
            {
                ++count;
            }
        }
    }
    std::cout << count << 'n';
}
相关文章: