我正在生成100個隨機數並將它們放在a中,數字應該是0-999。我寫了我的程序,並沒有打印隨機數字。 我感謝任何幫助。 這是我的代碼C程序bigneer
#include <stdio.h>
#defin S 100
int main()
{
int x;
int a [S];
a[S]=100;
for(x=0;x<s;x++){
printf(a[x]);
}
return 0;
}
我正在生成100個隨機數並將它們放在a中,數字應該是0-999。我寫了我的程序,並沒有打印隨機數字。 我感謝任何幫助。 這是我的代碼C程序bigneer
#include <stdio.h>
#defin S 100
int main()
{
int x;
int a [S];
a[S]=100;
for(x=0;x<s;x++){
printf(a[x]);
}
return 0;
}
兩件事:首先,int a [S]; a[S]=100
超過數組邊界(max是S-1
)。 其次,printf(const char* format, ...)
需要一個格式字符串,但在格式字符串的位置傳遞一個整數值(打開編譯器警告!)。所以寫printf("%d ", a[x])
,程序至少應該打印出一些數字(一旦你真的把任何數字分配給a
)。
這樣的:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define SIZE 100
#define RANGE 1000
int main(void){
srand(time(NULL));
int a[SIZE];
bool chosen[RANGE] = {0};
for(int i = 0; i < SIZE; ++i){
int select = rand() % RANGE;//select 0..RANGE-1
while(chosen[select]){//check duplicate
if(++select == RANGE)
select = 0;//reset
}
chosen[select] = true;//selected
a[i] = select;
}
//result
for(int i = 0; i < SIZE; ++i)
printf("%d ", a[i]);
puts("");
return 0;
}
請取[旅遊], 學習提出好的問題stackoverflow.com/help/how-to-ask, 作出[MCVE。 如果您正在尋找調試代碼的幫助,請參閱https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Yunnosch
'a [S] = 100;'超出界限陣列。 'a [S]'只能從0到99索引。 –
提示:打開編譯器警告('-Wall'代表gcc)。 – Paul