-4

我想以降序将数字写入数组 x[] 。例如,我将数组的长度输入为 3,但数字未列为 3、2、1。它写为 0 0 0。谁能告诉我需要做什么?

int main()
{
  int x[500000], size, i;
  printf("Enter the lenght of the array: ");
  scanf("%d", &size);

  for ( i = size; i > 0; i-- ) 
  {
    printf( "%4d", x[ i ] );
  } /* end for */
4

2 回答 2

0

You enter the LENGTH of the array, but this provides no informatio about element values. It is like I'm telling you: I give you 5 numbers, sort them. You can't sort them because you don't know the element values. The values that you get are just garbage values from memory.

It is a little bit unclear what you really want to do. If you just want to get an output like 3, 2, 1, put printf("%d ", i); inside for loop (and get rid of array). If you really want to sort some data, then you need to get the data into an array, then implement a sorting algoritm to sort it.

于 2013-11-14T17:18:59.243 回答
0

只需添加到您的代码中的一行将至少初始化您正在打印的元素:

int main()
{
  int x[500000], size, i;
  printf("Enter the lenght of the array: ");
  scanf("%d", &size);

  for ( i = size; i > 0; i-- ) 
  {
    x[i] = i;   // <<<<<<<<<<<<<< add this line
    printf( "%4d", x[ i ] );
  } 
}

如果您希望所有元素都具有相应的值,您可以这样做

int main()
{
  int x[500000], size, i;
  printf("Enter the lenght of the array: ");
  scanf("%d", &size);

  // initialize all the elements:
  for( i = 0; i < 50000; i++) x[i] = i;

  // check just a few:
  for ( i = size; i > 0; i-- ) 
  {
    printf( "%4d", x[ i ] );
  } 
}
于 2013-11-14T17:20:18.440 回答