【发布时间】:2019-03-01 19:09:57
【问题描述】:
此程序提示用户输入名称。然后它将使用两个 while 循环。一个 while 循环生成 3 个随机字母,然后是一个破折号,然后是另一个 while 循环以生成 3 个随机数字。我可以根据需要让程序执行此操作 3 次。
问题是它会为输入的三个名称中的每一个生成相同的三个随机数字和字母。我希望输入的每个名称都打印一组唯一的字母和数字。是和 srand() 函数有关吗?
还有一个问题,在输入第二个名字后打印字符后添加破折号,在打印输入第三个名字的字符后添加两个破折号。
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int nameCount = 0; // Hold the number of names entered by user
string randomID; // Used to concatenate the random ID for 3 names
string name; // To hold the 3 names entered by the user
int numberOfCharacters = 0;
int numberOfNumbers = 0;
int a;
srand(time(NULL));
while(nameCount < 3) {
cout << "\nEnter a name: ";
getline(cin, name);
while (numberOfCharacters < 3) {
randomID += static_cast<int>('a') + rand() %
(static_cast<int>('z') - static_cast<int>('a') + 1);
numberOfCharacters++;
}
randomID += "-";
while (numberOfNumbers < 3) {
randomID += static_cast<int>('1') + rand() %
(static_cast<int>('1') - static_cast<int>('9') + 1);
numberOfNumbers++;
}
cout << randomID;
nameCount++;
}
return 0;
}
【问题讨论】:
-
不是问题,但您可以删除代码中的所有静态强制转换。
static_cast<int>('a') + rand() % (static_cast<int>('z') - static_cast<int>('a') + 1)与'a' + rand() % ('z' - 'a' + 1)完全相同。原因见:en.cppreference.com/w/c/language/… -
为什么要输入名字?为什么不把
randomID打印出来再使用之前清除一下? -
这正是作业所需要的