我在基本程序中遇到有关数组最大值及其出现次数的问题。我不知道程序是如何编译的。我已经在纸上对其进行了测试,并且(在Visual Studio中编译),如果我最多给出十个值,它就可以正常工作,但是如果我在数组中超过十个数字,那么这个计数就太疯狂了。
这是代码。
rails generate #takes the name of generator as its 1st argument
rails generate devise #tells generate to lookup the devise namespace
# the next single argument `devise:install` is parsed by generator and
# calls the install task. The colon is use by [Rake][1] to call tasks within namespace
rails generate devise:install
# As already mentioned in previous answer and in devise docs
# here install is not a sub task but an argument passed to the devise task
rails generate devise user # this is typically the model devise would use
答案 0 :(得分:2)
首先,您应检查n
小于50。还应在单个语句周围添加括号,以免出现错误。
您还有一个问题,因为count
应该设置为1
,而不是0
,并且只有遇到相同的数字时才应该增加它。
C ++方式:max = *std::max_element(v, v+n);
和count = std::count(v, v+n, max);
。
答案 1 :(得分:2)
在第二个for
循环中,检查数组中的当前项目是否大于当前的最大项目;如果是真的,则将新的最大值设为当前项,并将count
设置为0-实际上应该将其设置为1。如果不大,则增加计数-这是另一个问题。如果当前数字小于最大值而不是最大值,则不应增加count
变量,但这就是您的代码所要做的。
这里是一个简单的解决方法,应该可以起作用:
int main()
{
int n, i, v[50], max, count = 0;
cout << "Number of elements = "; cin >> n;
for (i = 0; i < n; i++) {
cout << "v[" << i << "]=";
cin >> v[i];
}
max = v[0];
for (i = 0; i < n; i++)
if (max < v[i]) {
max = v[i];
count = 1;
}
else if(max == v[i])
++count;
cout << endl;
cout << "Maximum value, " << max << ", occurs " << count << " times.";
cout << endl;
system("pause");
return 0;
}
答案 2 :(得分:0)
#include "stdafx.h"
#include <iostream>
#include <map>
using namespace std;
int main()
{
int n, i, v[50], max, count = 0;
cout << "Number of elements = "; cin >> n;
for (i = 0; i < n; i++) {
cout << "v[" << i << "]=";
cin >> v[i];
}
map<int, int> m;
for (int i = 0; i < n; ++m[v[i++]]);
if (!m.empty())
{
const pair<int, int> p = *m.rbegin();
cout << endl;
cout << "Maximum value, " << p.first
<< ", occurs " << p.second << " times.";
cout << endl;
}
system("pause");
return 0;
}