c++ - C++ 生成随机词
问题描述
编写一个生成随机单词的程序(单词数 = n)。字的最大长度 = m。单词必须包含大小写字母。大写字母的概率必须等于 50%。
例子:
- 输入:2 4
- 输出: AbCd eFgH
我怎么做?
到目前为止,我想出了如何生成随机的大小字母。
我的代码:
#include <iostream>
using namespace std;
int main()
{
int n,m,s;
cin >> n;
cin >> m;
s=n*m;
char Tab[s];
for(int i=0; i<n*m; i++)
{
Tab[i]= 'A' + rand()%25;
}
for(int i=1; i<n*m; i++)
{
Tab[i+2]= 'a' + rand()%25;
}
for(int i=0; i<n*m; i++)
{
cout << Tab[i] << " ";
}
return 0;
}
解决方案
代码-
#include <iostream>
#include <time.h>
#include <string>
#include <stdlib.h>
using namespace std;
int main() {
int n,m;
cin>>n>>m;
srand(time(NULL));// without this rand() function might continuously give the same value
while(n--){
int stringLen = (rand() % m) +1; // getting random length
string s=""; // taking null string
for(int i=0; i<stringLen; i++){
if(rand() % 2 == 0 ){ // capital or small letter
s += 'A' + (rand() % 26);
}else{
s += 'a' + (rand() % 26);
}
}
cout<<s<<" ";
}
}
推荐阅读
- android-intent - Flutter:通过flutter执行代码时未收到PendingIntents
- r - select rows that match condition in several columns
- javascript - window.confirm 对话框不允许元素样式更改完成应用。任何解决方法?
- html - 如何在不离开它的情况下将制表键事件保留在自己的 div 中
- typescript - TypeScript 又一个带有不存在键的“prop”函数
- javascript - 从字符串中全局删除单个字符
- powershell - 无法添加引用的程序集 powershell 核心
- python - discord.py - 如果角色获得了用户没有的权限,则修改无法使用的角色的命令
- java - 反序列化时需要一个 List,但得到一个类 java.util.HashMap
- composer-php - Symfony\Component\Process\Exception\ProcessTimedOutException