gpt4 book ai didi

c++ - 显示1到9的数字在二维数组中出现的次数

转载 作者:行者123 更新时间:2023-11-27 23:47:34 25 4
gpt4 key购买 nike

我们要显示从1到9的数字在二维数组中出现的次数。我们不能使用 map 、 vector 或任何高级的东西。

这是我目前所拥有的:

    #include <iostream>
using namespace std;

int main()
{
//declare numbers array
int numbers[5][3] = {{1, 2, 7},
{2, 5, 3},
{1, 9, 4},
{2, 6, 5},
{7, 2, 2}};
//declare counts array
int counts[9];

//declare variable
int digit = 0; //keeps track of numbers from 1 through 9

while (digit <= 9)
{
for (int row = 0; row < 5; row++)
for (int col = 0; col < 3; col++)
//count the number of times the digit appears in the numbers
array
if (numbers[row][col] == digit)
counts[numbers[row][col]]++;
//end if
//end for
//end for
digit++; //look for next digit
} //end while

//display counts
for (int x = 1; x < 10; x++)
cout << "The number " << x << " appears "
<< counts[x] << " time(s)." << endl;
//end for

cin.get();
return 0;
} //end of main function

我可以让它显示“数字 1 出现(大量)次。”它将显示该句子 9 次,每个语句递增 1。问题是数量多。我如何让它显示正确的次数?

最佳答案

int counts[9];

这将创建数组,但不会初始化值,因此您会遇到未定义的行为! (编译器可能只是给你内存中已经存在的任何位,这可能会计算出一些非常大的数字)。

相反,您想将计数初始化为 0:

int counts[9] = {0};

关于c++ - 显示1到9的数字在二维数组中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49372317/

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