我的代码正在显示数组。如何显示给定整数重复的次数并显示重复的下标位置?
#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");
}
答案 0 :(得分:0)
我没有看到你的计数代码在矩阵上迭代。 'for'循环中没有提到'x'。
答案 1 :(得分: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 ++;
}
}
答案 2 :(得分: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;)有一个好的编码!