你好,我想添加for循环,该循环将打印我的代码20次或50次..但是我真的无法弄清楚,因为我已经添加了function,但它仍然只给出1个结果:D
#include <bits/stdc++.h>
using namespace std;
const int MAX = 36;
// Returns a string of random alphabets of
// length n.
string printRandomString(int n)
{
char alphabet[MAX] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z', '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9'};
string res = "";
for (int i = 0; i < n; i++)
res = res + alphabet[rand() % MAX];
return res;
}
// Driver code
int main()
{
srand(time(NULL));
int n = 20;
cout << printRandomString(n);
return 0;
}
答案 0 :(得分:2)
只需循环运行函数
int main()
{
srand(time(NULL));
int n = 20;
for (int i = 0; i < 50; ++i)
cout << printRandomString(n);
return 0;
}
旁注:#include <bits/stdc++.h>
is bad,using namespace std;
is bad,如果将它们组合在一起,则特别糟糕。
答案 1 :(得分:2)
您需要相应地在main中设置一个循环:
int len = 20 + ( rand() % ( 50 - 20 + 1 ) );
for(int i = 0; i< len; i++)
{
int n = 20 + ( rand() % ( 50 - 20 + 1 ) );
cout << printRandomString(n)<<endl;
}
以下是完整的工作代码。参见it working here:
#include <iostream>
using namespace std;
const int MAX = 36;
const int PRINT_MIN = 20;
const int PRINT_MAX = 50;
// Returns a string of random alphabets of length n.
string printRandomString(int n)
{
char alphabet[MAX] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z', '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9'};
string res = "";
for (int i = 0; i < n; i++)
res = res + alphabet[rand() % MAX];
return res;
}
// Driver code
int main()
{
srand(time(NULL));
int len = PRINT_MIN + ( rand() % ( PRINT_MAX - PRINT_MIN + 1 ) );
for(int i = 0; i< len; i++)
{
int n = PRINT_MIN + ( rand() % ( PRINT_MAX - PRINT_MIN + 1 ) );
cout << printRandomString(n)<<endl;
}
return 0;
}
答案 2 :(得分:1)
您的代码原样只会产生1个20个字符的字符串。如果要多次打印此字符串,则应将main()函数更改为以下内容:
int main()
{
srand(time(NULL));
int n = 20,m=30;
for(int i=0;i<m;i++)
{
cout << printRandomString(n);
}
return 0;
}
答案 3 :(得分:0)
我认为这是您想要实现的。
#include <iostream>
using namespace std;
const int MAX = 36;
char printRandomString()
{
char alphabet[MAX] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z', '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9'};
return alphabet[rand() % MAX];
}
// Driver code
int main()
{
int n;
scanf("%d",&n);
for(int i;i<n;i++){
printf("%c",printRandomString());
}
return 0;
}
如@Yksisarvinen所述,请尝试不要使用#include <bits/stdc++.h>
。