2010-11-10 56 views
1

我的代码正在显示数组。如何显示给定整数的重复次数并显示重复的下标位置?在二维数组中计数并显示出现

#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"); 
} 
+2

而你的问题是? – 2010-11-10 06:27:55

+0

如何编码以显示给定整数重复的次数,并显示重复的下标位置? – Luckwhy 2010-11-10 06:31:15

+0

这是一个功课题吗? – 2010-11-10 06:39:46

回答

0

我没有看到你的计数代码遍历矩阵。 'for'循环中没有提到'x'。

+0

噢。现在它显示次数。谢谢。 – Luckwhy 2010-11-10 06:48:41

+0

请告诉我如何显示下标位置。 – Luckwhy 2010-11-10 06:49:17

0

你应该更换你的代码:

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 ++; 
    } 
} 
+0

你是我做的,它显示的次数。我不知道如何显示数字重复的下标位置。 – Luckwhy 2010-11-10 06:56:39

+0

请帮助显示重复的下标位置。 – Luckwhy 2010-11-10 07:16:44

0

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

您可以显示下标位置的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)有良好的编码!