首页 > 解决方案 > C++ 生成随机词

问题描述

编写一个生成随机单词的程序(单词数 = n)。字的最大长度 = m。单词必须包含大小写字母。大写字母的概率必须等于 50%。

例子:

  1. 输入:2 4
  2. 输出: 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;
}

标签: c++loopsrandomchar

解决方案


代码-

#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<<" ";
    }
}

推荐阅读