C++ 随机数的字符串练习

C++ String excercise with random numbers

本文关键字:练习 字符串 随机数 C++      更新时间:2023-10-16

我必须做这个练习:

对学童的常见惩罚是多次写出相同的句子。编写一个C++独立的程序,它将写出以下句子一百次:"我将始终使用面向对象设计。你的程序应该对每个句子进行编号,并且它应该"意外地"在列表中的不同位置制作八个不同的随机拼写错误,这样它看起来像是人类手动输入的。

我的知识仅限于C随机数。我试过这个没有成功。我不能得到 8 个错误。正如我们所看到的,我得到了"错别字"的随机错误。

这是我的错误代码:

#include <iostream>
#include <ctime>
using namespace std;
int main()
{
string strPunish = "I will always use objectoriented design.";
int randFrom = 1;
int randTo = 100;
int typoCounter = 0;
srand(time(NULL));
int randNumber = randFrom + ( std::rand() % ( randTo - randFrom + 1 ) );
for (int i = 1; i <= 100; i++)
{
if ((i == randNumber) && (typoCounter != 8))
{
randFrom = i;
randNumber = randFrom + ( std::rand() % ( randTo - randFrom + 1 ) );
string strTypo = strPunish;
int randTypo = 0 + ( std::rand() % ( strTypo.length() - 0 + 1 ) );
strTypo.insert(randTypo, "TYPO");
cout << i << ": " << strTypo << endl;
typoCounter++;
}   
else
cout << i << ": " << strPunish << endl;
}
return EXIT_SUCCESS;
}

如上所述,既然是你的作业,你就应该自己解决。但是我会给你一些关于代码可能改进的线索:

  1. 首先,您应该将代码划分为小函数 - 这将使它更具可读性,并且更易于理解!
  2. 创建一个
  3. 包含范围[0, 99]中的所有数字的数组更容易,打乱它,只需选择前X行进行修改(其中X可以是任何东西!有关详细信息,请查看std::arraystd::shuffle
  4. 不要在代码中使用硬编码的数字!相反,您应该定义constexpr变量 - 这将使您的代码更具可读性(还记得(1)吗?
  5. 另外:使用randsrand不再常见,相反,最好使用<random>中的std::mt19937。此外,更常见的是看到<chrono>而不是<ctime>的用法。

备注:请注意,您需要确保选择要修改的行号是唯一;确保它(可能不会永远卡住(的最快方法是按照我在(2)中的建议进行操作。

我已经为您制作了整个程序:

#include <iostream>
#include <ctime>
void selectionSort(int[], int);
int main(void)
{
std::string punishStr = "I will always use objectoriented design."; // declaration
std::string tempStr = punishStr;
std::string typoStr = "TYPO";
int length = punishStr.length();
int location = 0;
short int count = 0;
int randoms[8] = {0};
srand(time(0)); // generates random different times
for (int i = 0; i < 8; i++)
{
randoms[i] = (rand() % 100) + 1; // creates 8 random numbers
}
selectionSort(randoms, 8); // sorts random numbers, for sake of being unbiased
for (int i = 0; i < 100; i++)
{
if (randoms[count] == i && count <= 8) // random number equals i
{
punishStr = tempStr;
location = (rand() % length) + 1;
std::cout << (i + 1) << ": " << punishStr.insert(location, typoStr) << std::endl;
count++;
}
else
std::cout << (i + 1) << ": " << tempStr << std::endl;
}
return 0;
}
void selectionSort(int a[], int n) // sorting algorithm
{
int i, j, min, temp;
for (i = 0; i < n - 1; i++)
{
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}

程序首先声明一些必要的变量,包括所需的八个零随机数。然后,通过使用 For 循环,它重新定义了所有 8 个数组元素,随机数范围在 1-100 之间。

之后,简单地对数组进行排序(否则它会有偏差,例如 54, 32...(,为了防止它,我们简单地像 32, 54 ... 一样排序。此后,它会检查计数器变量是否为 <= 8,如果是,则递增并显示拼写错误句子。否则,显示正确的句子。

它会一遍又一遍地重复,直到i小于 100。

希望它对你有用。

注意:输出太大了,最好你自己检查。