代码应显示阵列中最大数量的次数,因此对于以下输入(3,2,1,3),输出应为' 2'作为' 3'是最大数量,并发生两次。我想使用函数,我知道有一种更简单的方法可以解决它,但我只是想知道我的代码中的问题: -
#include<iostream>
using namespace std;
int frequency(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[j] == 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 = frequency(n, a);
cout << result << endl;
return 0;
}
答案 0 :(得分:1)
对于初学者来说,C ++标准不支持可变长度数组。因此,您应该使用某个容器而不是数组,例如std::vector<int>
。
此外,程序具有未定义的行为,因为至少在此循环中
while(j<n){
if(a[j+1]> max){
max = a[j+1];
}
j++;
}
尝试访问表达式a[j+1]
中的数组之外的内存。
最后,函数总是返回0,因为函数最外层范围内的变量count
设置为零并且永远不会更改。
可以使用迭代器编写一般方法。
例如
#include <iostream>
#include <iterator>
#include <vector>
template <typename InputIterator>
size_t count_maximum_value( InputIterator first, InputIterator last )
{
size_t count = 0;
if ( first != last )
{
++count;
typename std::iterator_traits<InputIterator>::value_type max = *first;
while ( ++first != last )
{
if ( max < *first )
{
max = *first;
count = 1;
}
else if ( not ( *first < max ) )
{
++count;
}
}
}
return count;
}
int main()
{
size_t n = 0;
std::cout << "Enter the number of integers: ";
std::cin >> n;
if ( n )
{
std::vector<int> v( n );
std::cout << "Enter " << n << " integers: ";
for ( size_t i = 0; i < n; i++ ) std::cin >> v[i];
std::cout << "The maximum value is encountered "
<< count_maximum_value( v.begin(), v.end() )
<< " time(s)"
<< std::endl;
}
return 0;
}
程序输出可能看起来如下
Enter the number of integers: 4
Enter 4 integers: 3 2 1 3
The maximum value is encountered 2 time(s)
答案 1 :(得分:0)
您正在将a[j+1]
与max
进行比较。我建议你使用a[j]
。您似乎正在跳过输入中的第一个数字。
答案 2 :(得分:0)
从count = 1
开始,而不是count = 0
,并删除循环中重新计算的次数。
您从0开始,然后在找到与其匹配的第二个条目时添加1。这就是为什么你要一个人离开的原因。
答案 3 :(得分:0)
检查评论
#include<iostream>
using namespace std;
int frequency(int n, int a[]) {
int j=0,max,count=0;
max = a[j];
while(j<n){
if(a[j]> max){ // 1. j+1 crosses lenth of array
max = a[j];
}
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; //2. re declaration and you are not returning this
//for(int j = i; j < n;j++) //3. No need of extra loop it make count extra because you are starting at j=i
//if(a[j] == a[i] && a[j] == max)
if(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 = frequency(n, a);
cout << result << endl;
return 0;
}