【问题标题】:Count and display occurrences in 2D array计算并显示二维数组中的出现次数
【发布时间】:2011-05-07 16:57:15
【问题描述】:

我的代码很好地显示了数组。如何显示给定整数的重复次数,并显示重复的下标位置?

#include <iostream>
#include <cmath>
#include <iomanip>
#include <ctime>

using namespace std;
int main()
{
    int table [10][10]={{0},{0}};
    int repeat=0;
    int count=0;
    int r=0;
    int c=0;
    //seeding the random function
    srand(static_cast<int>(time(0)));

    for(r=0; r<10; r++)//row
    {
        for(c=0; c<10; c++)
        {
            table[r][c] = 50+rand() %(100-50+1);
            cout << table[r][c]<<"  ";

        }
        cout<<endl;
    }
    cout<<"Enter the number to know how many times it is repeated(50 to 100): ";
    cin>>repeat;
    for (int x=0; x<10; x++)
    {
        if(repeat==table[r][c])
            count+=1;

    }

    cout<<"the number "<<repeat<<" appeared"<<count<<" times."<<endl;
    //display new line

    system("pause");
}

【问题讨论】:

  • 如何编写代码来显示给定整数的重复次数并显示重复的下标位置?
  • 有点,我是从一本书中自学的。
  • 混合制表符和空格缩进通常是个问题;使用所有工具(包括您一开始可能没有想到的工具,例如 SO)获得一致结果的最佳方法是让您的编辑器在您按 Tab 键时插入空格。 (我在这里为你重新格式化了代码。)

标签: c++ arrays multidimensional-array


【解决方案1】:

我没有看到您的计数代码在矩阵上进行迭代。 'for' 循环中的任何地方都没有提到'x'。

【讨论】:

  • 哦,是的。现在它正在显示次数。谢谢。
  • 请告诉我如何显示下标位置。
【解决方案2】:

你应该替换你的代码:

for (int x=0; x<10; x++)
{
    if(repeat==table[r][c])
        count+=1;
}

到这里:

for (r = 0; r < 10; r ++)
{
    for (c = 0; c < 10; c ++)
    {
        if(table[r][c] == repeat)    // checking
             count ++;
    }
}

【讨论】:

  • 是的,我这样做了,它正在显示次数。我不知道如何显示数字重复的下标位置。
  • 请帮忙显示下标重复的位置。
【解决方案3】:

有两种方法可以做到这一点:

您可以在 for 循环中显示下标位置:

puts ("Locations:");
for (r = 0; r < 10; r ++)
{
    for (c = 0; c < 10; c ++)
    {
        if(table [r][c] == repeat)            // checking
        {
            printf ("[%i, %i]\n", r, c);      // display where it is
            count ++;
        }
    }
}

或者你可以创建一个特殊的下标数组:

int rs [100];    // rows and columns indexes of repeated subscripts
int cs [100];    //

for (r = 0; r < 10; r ++)
{
    for (c = 0; c < 10; c ++)
    {
        if(table [r][c] == repeat)            // checking
        {
            // no printf code here
            rs [count] = r;
            cs [count] = c;
            count ++;
        }
    }
}

// subscripts can be displayed or used in math algorithm now:

puts ("Locations:");
for (int i = 0; i < count; i ++)
    printf ("[%i, %i]", rs [i], cs [i]);

最后一种方法不是最优的,但它适合学习 C ;) 好好编码!

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 2022-01-07
    • 1970-01-01
    • 2023-04-02
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    相关资源
    最近更新 更多