我试图随机生成5个字符串,看起来像“A1,B3,C7,D2,I8”,没有重复。最终结果应该是一个工作函数,它给我一个容易面对的字母和数字。 这是我所做的功能,顺便说一下这个功能的问题 它只给我数字。
using namespace std;
char letters[]= {'A','B','C','D','E','F','G','H','I','L'};
int Num[11];
char pGuess[10];
string generateSetOfNumbers()
{
int G = rand() % 10;
int nOut = rand() % 10 + 1;
char lOut = letters[G];
int Max = 5;
int Min = 0;
string culo = lOut + to_string(nOut);
{
int G = rand() % 10;
int nOut = rand() % 10 + 1;
char lOut = letters[G];
int Max = 5;
int Min = 0;
string culo1 = lOut + to_string(nOut);
return culo1;
}
{
int G = rand() % 10;
int nOut = rand() % 10 + 1;
char lOut = letters[G];
int Max = 5;
int Min = 0;
string culo2 = lOut + to_string(nOut);
return culo2;
}
{
int G = rand() % 10;
int nOut = rand() % 10 + 1;
char lOut = letters[G];
int Max = 5;
int Min = 0;
string culo3 = lOut + to_string(nOut);
return culo3;
}
{
int G = rand() % 10;
int nOut = rand() % 10 + 1;
char lOut = letters[G];
int Max = 5;
int Min = 0;
string culo4 = lOut + to_string(nOut);
return culo4;
}
}
答案 0 :(得分:0)
这些代码块没用。你的功能总是在这里返回:
string culo = lOut + to_string(nOut);
{
int G = rand() % 10;
int nOut = rand() % 10 + 1;
char lOut = letters[G];
int Max = 5;
int Min = 0;
string culo1 = lOut + to_string(nOut);
return culo1; // function returns, no further execution
}
您是否要使用if()
else if()
级联检查某些条件以有条件地执行这些代码块?
答案 1 :(得分:0)
这是实现你想要的一种方式:
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <random>
// build an array of strings A1-9 to I1-9
// then shuffle it randomly (like a deck of cards)
std::vector<std::string> make_candidates()
{
// this builds the array
std::vector<std::string> result;
// for each number 1 to 9...
for(int i = 1 ; i < 10 ; ++i)
{
// for each letter A to I...
for(char c = 'A' ; c < 'J' ; ++c) {
// build a string of Letter, Number and push it to the
// top of the 'deck'
char s[2] = { c, char('0' + char(i)) };
result.emplace_back(std::begin(s), std::end(s));
}
}
// random device delivers true random numbers (on most systems)
std::random_device rd {};
// make a pseudo-random engine, seeded with a real random number
auto eng = std::default_random_engine(rd());
// use the engine to shuffle our 'deck' of results
std::shuffle(std::begin(result), std::end(result), eng);
return result;
}
// pull the last string off the given 'deck'
std::string next_candidate(std::vector<std::string>& candidates)
{
auto result = std::move(candidates.back());
candidates.pop_back();
return result;
}
int main()
{
// make a shuffled 'deck' of 'cards' from A1 to I9, but in
// random order
std::vector<std::string> candidates = make_candidates();
// pick the top 5 and print them
std::cout << next_candidate(candidates) << std::endl;
std::cout << next_candidate(candidates) << std::endl;
std::cout << next_candidate(candidates) << std::endl;
std::cout << next_candidate(candidates) << std::endl;
std::cout << next_candidate(candidates) << std::endl;
return 0;
}
示例输出:
F6
F4
I3
F3
G9