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

Displays the number of times the numbers from 1 through 9 appear in a two-dimensional array

本文关键字:二维数组 数字 显示      更新时间:2023-10-16

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

这是我到目前为止所拥有的:

#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};

即使您修复了第一个问题并初始化了int counts[9] = {0};,您仍然会遇到未定义的行为,并最终尝试访问超出数组边界末尾的值,因为声明:

int counts[9] = {0};

使计数的有效索引0 - 81 - 9因此,当您迭代counts[x]时:

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

您调用未定义的行为尝试读取counts[9]。如果要使用x = 1; x < 10,您需要访问counts[x-1]

更好的方法是循环x = 0; x < 9,只需将1添加到:

cout << "The number " << x + 1 << " appears "

在增加counts数组中的值以存储数字的频率时,必须采取相同的索引小心1 - 9(注意:这些比您的实际数组索引0 - 8高 1-,这似乎在很大程度上是本练习的目的),例如,在考虑数字出现频率时必须减去11 - 9以便适当的相应索引0 - 8保存相关值, 例如

counts[numbers[i][j] - 1]++;    /* indexes are 0-8 */

始终遍历数组边界(而不是在数组边界之外)将防止此类问题。

对逻辑进行简短的重写,您可以执行以下操作:

#include <iostream>
#define NCOLS  3
#define NRANGE 9
using namespace std;
int main (void) {
int numbers[][NCOLS] = {{1, 2, 7},
{2, 5, 3},
{1, 9, 4},
{2, 6, 5},
{7, 2, 2}},
nrows = sizeof numbers / sizeof *numbers,   /* rows */
counts[NRANGE] = {0};                   /* frequency */
for (int i = 0; i < nrows; i++)             /* fill counts */
for (int j = 0; j < NCOLS; j++)
if (1 <= numbers[i][j] && numbers[i][j] <= NRANGE)
counts[numbers[i][j] - 1]++;    /* indexes are 0-8 */
for (int x = 0; x < NRANGE; x++)            /* display counts */
cout << "The number " << x + 1 << " appears "
<< counts[x] << " time(s)." << endl;
#if defined (_WIN32) || defined (_WIN64)
cin.get();
#endif
}

(如果您使用cin.get();来防止终端在 Windows 上关闭,则应将其包装在预处理器条件中,因为其他操作系统不需要这样做)

示例使用/输出

$ ./bin/frequency_array
The number 1 appears 2 time(s).
The number 2 appears 5 time(s).
The number 3 appears 1 time(s).
The number 4 appears 1 time(s).
The number 5 appears 2 time(s).
The number 6 appears 1 time(s).
The number 7 appears 2 time(s).
The number 8 appears 0 time(s).
The number 9 appears 1 time(s).