提示用戶輸入 10 個整數,如果有重復的數字,它將再次詢問 10 個整數,如果沒有重復的數字,它將結束回圈。
這是預期的輸出:
如果我輸入 10 個數字,程式將檢查陣列是否有重復的數字,如果有,它會要求用戶再次輸入 10 個整數。如果沒有重復的數字,回圈將結束。
Enter 10 elements in the array :
Input 1: 1
Input 2: 2
Input 3: 3
Input 4: 4
Input 5: 5
Input 6: 5
Input 7: 5
Input 8: 6
Input 9: 7
Input 10: 8
5 is repeated, please enter numbers again // the 5 repeated in the array.
Enter 10 elements in the array :
Input 1: 1
Input 2: 2
Input 3: 3
Input 4: 4
Input 5: 5
Input 6: 6
Input 7: 7
Input 8: 8
Input 9: 9
Input 10: 0
There are no repeated numbers!
#include<stdio.h>
int main()
{
int array[10];
int i,j ,num=10;
int n = sizeof(array)/sizeof(array[0]);
int visited[n];
do{
printf("\n");
printf("Enter %d elements in the array : \n", num);
for(i=0;i<n;i )
{
printf("Input %i: ",i 1);
scanf("%d", &array[i]);
}
for(i=0; i < n; i )
if(visited[i] == 0){
int count = 1;
for(j = i 1; j < n; j ) {
// if appears again in the array
if(array[i] == array[j])
{ // increase count & mark index visited
count ;
visited[j] = 1;
}
} //
if(count >= 1){
printf("%d is repeated, please enter numbers again ",array[i]);
printf("\n");
break;
}else{
printf("There are no repeated numbers!");
break;
}
}
}while(!array[i]);
}
uj5u.com熱心網友回復:
可變長度陣列visited未初始化
int visited[n];
例如這個 if 陳述句
if(visited[i] == 0){
呼叫未定義的行為。
這個 if 陳述句
if(count >= 1){
printf("%d is repeated, please enter numbers again ",array[i]);
printf("\n");
break;
沒有意義,因為即使在源陣列中沒有重復一個值,但最初count設定為 1
if(visited[i] == 0){
int count = 1;
無需定義輔助陣列即可解決問題。
以及 do-while 陳述句中的條件
}while(!array[i]);
也沒有意義。
該程式可以看起來例如以下方式
#include <stdio.h>
int main( void )
{
enum { N = 10 };
int array[N];
int repeated = N;
do
{
printf("\n");
printf( "Enter %d elements in the array :\n", N );
for ( int i = 0; i < N; i )
{
printf( "Input %i: ", i 1 );
scanf( "%d", &array[i] );
}
repeated = N;
for ( int i = 0; i < repeated; i = repeated == N )
{
int j = i 1;
while ( j < N && array[j] != array[i] ) j ;
if ( j != N ) repeated = i;
}
if ( repeated != N )
{
printf( "%d is repeated, please enter numbers again.\n", array[repeated] );
}
else
{
puts( "There are no repeated numbers!" );
}
} while( repeated != N );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/522511.html
