C:最大数字,输出错误。 RAND()

时间:2018-02-05 19:06:22

标签: c arrays random

该程序使用rand()创建随机数。用户输入将作为整数创建的随机数。该程序还找到了最大的数字。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

  int main(void)
{
  srand(time(NULL));
  int size;
  int i;
  int array[0];

  printf("\nSize of random array: ");
  scanf("%d", &size);

  for (i = 0; i <  size; i++){
    array[i] = rand() % 100 + 1;;
  }

  for (i=0; i < size; i++){
       printf("%d ", array[i]);
      }

 int largest =0;

for (i = 1; i < size; i++)
{
      if (largest < array[i])
              largest = array[i];
      }
printf("\n largest element present in the given array is : %d\n", largest);

    return 0;
}

我正在使用在线C编译器。 (我使用的是Atom编辑器,但我的代码在那里没有做任何事情)。 输出应该是这样的:

  

随机数组的大小:6
  0 6 10 21
  给定数组中存在的最大元素是:21

但我得到了这个:

  

随机数组的大小:6
  0 6 0 0 -433525051 32757
  给定数组中存在的最大元素是:32757

为什么我会得到这么大的数字?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

对于C,您可以在开头静态分配内存,也可以使用malloc / calloc动态分配内存(还有一些其他方法)。由于您正在读取用户的大小数组,因此可能需要动态内存分配。动态分配内存需要注意一些事项。你总是要检查分配是否成功并释放你的记忆。您可以在此处阅读更多内容:https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm

使用OP示例代码的示例解决方案:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {

srand(time(NULL));
int size = 0;
int i;
int largest;
// You must declare a pointer to allocate space on the heap
int *array; 

// Loop until user enters a valid size
while (size <= 0) {

    printf("\nPlease enter the size of random array: ");
    scanf("%d", &size);

    if (size <= 0) 
      printf("Please enter a number above 0.");

}

// Set the size as your input size  
array = malloc(sizeof(int) * size); 

// Always check if your memory allocation was successful...
// Probably better ways to handle than to simply exit out
if(array == NULL) {

    printf("malloc of size %d failed!\n", size);
    exit(1); 

}

for (i = 0; i <  size; i++) {

  array[i] = rand() % 100 + 1;;

}

for (i = 0; i < size; i++) {

  printf("%d ", array[i]);

}

// Set the largest value as the first element in the arr
largest = array[0]; 

for (i = 1; i < size; i++) {

  if (largest < array[i]) {
        largest = array[i];
  }
}

printf("\nLargest element present in the given array is : %d\n", largest);

// Always FREE your allocated memory
free(array); 

return 0;

}

答案 1 :(得分:2)

您正在声明包含0个元素的int类型数组:int array[0];

相反,您需要使用malloc(以及随后的free)在堆上分配内存,或者您需要声明特定大小的数组并限制用户。

示例:

int* array; // <- declare a pointer

printf("\nSize of random array: ");
scanf("%d", &size);

array = malloc(sizeof(int)*size); // sizeof(int) * size gives us enough memory
// do something with array then free when done
free(array);

或者

int array[255]; // max of 255 elements

printf("\nSize of random array: ");
scanf("%d", &size);

if (size > 255) {
    fprintf(stderr, "Size greater than max\n");
    return -1;
}

访问数组边界之外的元素会导致未定义的行为;换句话说,可能按预期工作,或可能返回完全垃圾(在您的情况下会发生)。

希望可以提供帮助。

相关问题