gpt4 book ai didi

c - 获取要打印到屏幕的 arrayDisplay()_fucntion,这是一个已使用 srand() 填充的数组。

转载 作者:行者123 更新时间:2023-11-30 16:36:30 25 4
gpt4 key购买 nike

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

/*global constant array size*/
#define SIZE 10

/*prototyping*/
void displayArray(int *a);

int main()
{
int numbers[SIZE];
int x,inner,outer,temp;

这是为数组元素生成随机值。

   /*populate the array*/
srand((unsigned)time(NULL)); //seed randomizer
for(x=0;x<SIZE;x++)
{
numbers[x] = (rand() % 1000) + 1; //display random numbers between 1-
1000
}

/*display the unsorted array*/
displayArray(numbers);

这是冒泡排序,我调用函数 arrayDisplay 来输出每一步的交换,直到排序。

   /*sort the array*/
for(outer=0;outer<SIZE;outer++)
{
for(inner=outer+1;inner<SIZE;inner++)
{
if(numbers[outer] > numbers[inner])
{
temp = numbers[inner];
numbers[inner] = numbers[outer];
numbers[outer] = temp;
arrayDisplay(numbers);
}
}
}
/*display the sorted array*/
displayArray(numbers);

return 0;
}

这是函数 displayArray(),在调用时应该仅通过 rand 显示随机值。

void displayArray(int *a){
int x;

for(x=0;x<SIZE;x++)
{
printf("%4d",x+1);
}
putchar('\n');

return;
}

我从这个函数得到的输出是 1 - 10 作为元素值,而不是应该显示的随机值,我哪里出错了?

最佳答案

问题出在displayArray函数上:如果printf的第二个参数是x+1,则会打印:

1 2 3 ... 10

您应该更改printf并使用a指针:

printf("%4d",a[x]);

关于c - 获取要打印到屏幕的 arrayDisplay()_fucntion,这是一个已使用 srand() 填充的数组。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48438855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com