我想将一个随机数与一些字母数字字符交织在一起,例如:H2E5L6L3O5与随机数25635→混合。我知道%1d控制间距,但我不知道如何在随机数之间插入文本,也不知道如何实现这一点。
代码:
int main(void) {
int i;
srand(time(NULL));
for (i = 1; i <= 10; i++) {
printf("%1d", 0 + (rand() % 10));
if (i % 5 == 0) {
printf("\n");
}
}
return 0;
}顺便说一句,如果我的随机数生成器不是很好,我愿意接受建议--谢谢
发布于 2014-03-11 22:11:47
如果您不介意使用C++11,您可以使用以下内容:
#include <iostream>
#include <random>
#include <string>
int main() {
std::random_device rd;
std::default_random_engine e1(rd());
std::uniform_int_distribution<int> uniform_dist(0, 9);
std::string word = "HELLO";
for (auto ch : word) {
std::cout << ch << uniform_dist(e1);
}
std::cout << '\n';
}...which产生的例子有:
H3E6L6L1O5如果您使用的是较旧的编译器,则可以使用标准C库中的rand和srand来处理随机数:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
int main() {
std::srand(std::time(NULL));
std::string word = "HELLO";
for (int i = 0; i < word.size(); ++i) {
std::cout << word[i] << (rand() % 10);
}
std::cout << '\n';
}https://stackoverflow.com/questions/22337633
复制相似问题