gpt4 book ai didi

c++ - C++将随机值放在乘法图表中(嵌套循环)

转载 作者:行者123 更新时间:2023-12-02 10:02:41 25 4
gpt4 key购买 nike

我为整数1 ... 10创建了一个乘法表。这是代码:

for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
std::cout << "\t" << i * j;
}
std::cout << std::endl;
}

我的输出是这样的:
1   2   3   4   5   6   7   8   9   10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

我遇到的问题是我需要在乘法表中插入一个表示错误值的随机数。例如:
1   2   3   4   5   6   7   8   9   10
2 4 6 8 10 12 14 16 18 20
3 6 9 13 15 18 21 24 27 30

如本例所示,错误值是13,其中3 x 4 = 12,但是数字13。

我浏览了无数StackOverFlow帖子和互联网。

我应该使用另一个循环插入随机数吗?如果是这样,该怎么办?

最佳答案

您可以为此使用<random>头文件。

std::random_device rd;
std::mt19937 gen(rd());
// it produces uniformly distributed random integers in the range [a, b] (both inclusive)
std::uniform_int_distribution<> dis(0, 1); // either add 0 or 1 (1 will be the error -- can change a,b according to your need)

for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
std::cout << "\t" << i * j + dis(gen); // just add the error value to your multiplication
}
std::cout << std::endl;
}

关于c++ - C++将随机值放在乘法图表中(嵌套循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61812943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com