fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. int main() {
  6. // 1. 定义并初始化数组a为1-10的整数
  7. int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  8.  
  9. // 2. 输出初始数组(若需要)
  10. printf("初始数组:");
  11. for(int i=0;i<10;i++){
  12. printf("%d ",a[i]);
  13. }
  14. printf("\n");
  15.  
  16. // 3. 随机打乱数组(修正原代码逻辑)
  17. srand((unsigned int)time(NULL)); // 只需要初始化一次随机种子
  18. for(int i=9;i>0;i--){
  19. int j = rand() % (i + 1); // 生成0~i的随机索引,确保范围正确
  20. int temp = a[i];
  21. a[i] = a[j];
  22. a[j] = temp;
  23. }
  24.  
  25. // 4. 输出打乱后的数组
  26. printf("打乱后数组:");
  27. for(int i=0;i<10;i++){
  28. printf("%d ",a[i]);
  29. }
  30. printf("\n");
  31.  
  32. return 0;
  33. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
初始数组:1 2 3 4 5 6 7 8 9 10 
打乱后数组:4 7 8 3 5 1 9 10 6 2