//This code gives randomly generated alphabets and if equal will
//cout the alphabet which is equal
1 #include <iostream>
2 #include <cstdlib>
3 #include <ctime>
4 using namespace std;
5 int main()
6 {
7 int a;
8 char array[10];
9 srand (time(0));
10 for (int i=0; i<10; i++)
11 {
12 a=rand() %26;
13 a=a+97;
14 array[i]=char(a);
15 }
16 for (int i=0; i<10; i++)
17 {
18 for (int j=0; j<10; j++)
19 {
20 if (array [i]==array [j]);
21 {
22 cout <<array[i] <<" " <<array[j];//if alphabet 'c' is at indecis 2,5,8
//then output should be like that of
// only 22 no statement but actually it does
// not give this answer but gives wrong output
//c c
//c c
//c c
23 }
24 cout << endl;
25 }
26 }
27 return 0;
28 } //program end
我的问题是如何检查随机生成的字母表是否相等,例如在22数字行中它应该给出相等字母表的输出如果它们相等但是它没有给出相等的字母表这个代码中的错误提到错误的陈述或帮助我我将如何得到正确的答案
其实我想制作一个应该告诉我单个生成的字母表有多少次出现在数组中的程序
答案 0 :(得分:0)
根据你的评论,你正在寻找能够做到这一点的事情:
#include <random>
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
int main(){
::std::vector<char> letters(10);
::std::vector<char> unique;
::std::random_device rd;
::std::mt19937 mt(rd());
::std::uniform_int_distribution<char> dis('a', 'z');
auto random = ::std::bind(dis, mt);
// fill the vector with random letters
for(char & l : letters){
l = random();
}
int max_count = 0;
char appeared_most = ' ';
// get a vector of all the unique values
::std::unique_copy(letters.cbegin(), letters.cend(), ::std::back_inserter(unique));
// find the first value to appear most if two values appear equally
// the first will be chosen
for(const char & l : unique){
int count = ::std::count(letters.cbegin(), letters.cend(), l);
if(count > max_count){
max_count = count;
appeared_most = l;
}
}
::std::cout << appeared_most << " " << max_count ;
}
我在这里有一个工作样本:http://coliru.stacked-crooked.com/a/53c953576e0db756