gpt4 book ai didi

c - 与 C 中的函数传递的数组一起堆叠

转载 作者:太空宇宙 更新时间:2023-11-04 04:03:03 25 4
gpt4 key购买 nike

如何使用将从函数传递的数组中的信息?

 #include <stdio.h>

double get_number(double[]);

main {

double x, z[100];
char m;

do {
x = get_number[z];
printf("More numbers?");
scanf (" %c", &m);

}
while ((m == 'Y')||(m == 'y'))
}


double get_number(double arr[])
{
printf ("Please enter number : ?");
scanf("%d", &arr);
return arr;
}

例如当用户按几次 Y 并用两个或三个数字填充数组时。我如何使用这些数字进行操作?计算它们或只是展示它们。

最佳答案

使用 for() 循环。

for (int i = 0; i < array_size; i++) {
printf ("Number at index %d: %f", i, arr[i]);
}

当然,你需要事先知道尺寸。并且不要将 scanf() 与这样的数组一起使用,为什么不:

double get_input ()
{
double number = 0;

printf ("Please enter number: ");
scanf ("%d", &number);

return number;
}

将数组长度定义为固定值:

#define ARRAY_SIZE 1024

如果您需要更多,请增加该值或考虑使用列表结构。

希望对你有帮助

编辑

如果你想求和,比如你需要先初始化数组:

double array[ARRAY_SIZE];
for (int i = 0; i < ARRAY_SIZE; i++) array[i] = 0;

然后你得到输入:

char input;
int counter = 0;
do {
if (counter > ARRAY_SIZE) break; // dont cause a segmentation fault

scanf ("%c", &input);
double number = get_input();
array[counter] = number;

} while (input == 'Y' || input == 'y');

然后完成后,只需遍历数组并对其求和:

int sum = 0;
for (int i = 0; i < ARRAY_SIZE; i++) {
sum += array[i];
}

关于c - 与 C 中的函数传递的数组一起堆叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9547791/

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