C 如何在数组中查找不同的值
我想在数组中找到类似的值。因此,如果值不相似,计数器将增加1。代码:C 如何在数组中查找不同的值,c,C,我想在数组中找到类似的值。因此,如果值不相似,计数器将增加1。代码: struct station{ int d; //destination, one-way journey, no return int counter; int depart[10]; }; int main() { int n = 0; //number of stations int k = 0; //k is how many route one station can go
struct station{
int d; //destination, one-way journey, no return
int counter;
int depart[10];
};
int main()
{
int n = 0; //number of stations
int k = 0; //k is how many route one station can go
scanf("%d%d",&n, &k);
//declare array of stations based on input, n.
struct station list[n];
//Initialization
for(int i=0; i < n; i++){
list[i].d = 0;
list[i].counter = 0;
}
for(int i=0; i < n; i++){
int to;
scanf("%d", &to);
list[i].d = to-1;
}
//this is where the problem is
int ds = 0; //depart station
for(int ds=0; ds < n; ds++){ // n is number of station
list[ds].depart[list[ds].counter] = ds;
list[ds].counter = list[ds].counter + 1;
int next = list[ds].d;
for( int j = 0; j < k; j ++){ //k is how many route one station can go**
list[ next ].depart[ list[ next ].counter ] = ds;
if(list[ next ].depart[ list[ next ].counter ] != list[ next ].depart[ list[ next ].counter -1 ] ){
list[ next ].counter = list[next].counter + 1;
}
next = list[next].d;
}
}
for(int i=0; i < n; i++){
printf("station [%d]: counter = %d: ", i+1 , list[i].counter);
for(int j=0; j < list[ i ].counter; j++){
if (list[i].depart[j] != list[i].depart[j-1] ){
printf("%d,", list[i].depart[j] );
}
}
printf("\n");
}
return 0;
}
输入方式为:(车站数量)(一个车站可以走多少条路线)
(1号站去)
(第二站去)
(第三站去)
(第四站去)
(5号站去) 这是我当前的输出:
station [1]: counter = 3: 1,2,3
station [2]: counter = 2: 2,3
station [3]: counter = 2: 2,3
station [4]: counter = 2: 4,5
station [5]: counter = 2: 4,5
注:站2和3应在输出中显示1,而不仅仅是2和3
我以前试过这个:
int ds = 0; //depart station
for(int ds=0; ds < n; ds++){ // n is number of station
list[ds].depart[list[ds].counter] = ds;
list[ds].counter = list[ds].counter + 1;
int next = list[ds].d;
for( int j = 0; j < k; j ++){
list[ next ].depart[ list[ next ].counter ] = ds;
list[ next ].counter = list[next].counter + 1;
next = list[next].d;
}
}
请显示变量定义。您提供的代码不生成“输出”-它没有任何
printf
或类似语句。请显示生成输出的代码。请提供一个@KamilCuk,我已根据您所说的内容进行了更改。
int ds = 0; //depart station
for(int ds=0; ds < n; ds++){ // n is number of station
list[ds].depart[list[ds].counter] = ds;
list[ds].counter = list[ds].counter + 1;
int next = list[ds].d;
for( int j = 0; j < k; j ++){
list[ next ].depart[ list[ next ].counter ] = ds;
list[ next ].counter = list[next].counter + 1;
next = list[next].d;
}
}
station [1]: counter = 4: 1,1,2,3
station [2]: counter = 4: 1,2,2,3
station [3]: counter = 4: 1,2,3,3
station [4]: counter = 4: 4,4,5,5
station [5]: counter = 4: 4,4,5,5