我正在學習在 C 上編程,我正在嘗試創建一個程式來掃描用戶建立的一定數量的數字,并將它們存盤在我稍后將使用的陣列中,但是用戶引入的數字不能重復,所以我試圖通過 for 回圈內的比較來實作這個限制。我已經嘗試過其他型別的回圈,但我無法使其正常作業。
謝謝!
到目前為止,這是我的代碼:
#include<stdio.h>
int main ()
{
int n;
int i;
int num;
printf("Introduce the amount of numbers you will register \n");
scanf("%d",&n);
int N[n];
printf("Introduce your numbers \n");
for (i=0; i<n; i )
scanf ("%d",&num);
{
if (num == N[i])
{
printf("You already introduced this number, try again");
}
N[i]=num;
printf("____________ \n");
}
getchar ();
getchar ();
return 0;
}
當我運行這個程式時,輸出就是這個,我不知道為什么
Introduce the amount of numbers you will register
5
Introduce the first value
1
____________
____________
____________
____________
You already introduced this number, try again ____________
--------------------------------
uj5u.com熱心網友回復:
對于初學者,您可能不會宣告具有零元素的可變長度陣列
int n=0;
//...
int N[n];
您需要在變數 n 中輸入正值后宣告陣列。
int n;
//...
printf("Introduce the amount of numbers you will register");
scanf("%d",&n);
int N[n];
此外,由于陣列未初始化,因此此比較
if (num == N[i])
呼叫未定義的行為。
您還必須在回圈中輸入值,
您需要撰寫如下內容
for ( i=0; i<n;)
{
scanf ("%d",&num);
int j = 0;
while ( j != i && num != N[i] ) j;
if ( j != i )
{
printf("You already introduced this number, try again");
}
else
{
N[i ] = num;
printf("____________ \n");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/374248.html
