C:最大数,输出错误。兰德()

标签 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 编辑器,但我的代码在其中没有执行任何操作)。 输出应该是这样的:

Size of random array: 6
0 6 10 21
largest element present in the given array is : 21

但是我得到了这个:

Size of random array: 6
0 6 0 0 -433525051 32757
largest element present in the given array is : 32757

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

最佳答案

对于 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;

}

关于C:最大数,输出错误。兰德(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48629727/

相关文章:

c - C 中的简单随机数生成器不起作用

c - 尝试替换文件中的文本会引发错误

c - C中的默认 union 和结构对齐?

python - 带和不带放回的加权随机选择

c - 在 C 中将数组中的数字排序为列和行

c++ - 为什么概念上的存储分配与实际不同?

c - gcc -g 调试标志是否影响程序执行?

c - 当给定一个大数字时程序崩溃

php - 如何从数组键创建变量

ios - 理解 swift 3 中的平等?