arrays - ANSI C - 数组的较高元素

标签 arrays c numbers ansi-c

我的代码在获取 5 个元素的数组中的最大数字时遇到了一些问题,这是我的代码:

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

float timerunner1[4];
int x;

int main() {

for(x=1;x<6;x++) {
    printf("Give me the time of runner 1: ");
    scanf("%f",timerunner1[x]);
}
return 0;
}

这工作得很好,输出是:

Give me the time of runner 1:  14
Give me the time of runner 1:  3
Give me the time of runner 1:  10
Give me the time of runner 1:  5
Give me the time of runner 1:  2

如何获取数组中的最大和最小数? 也许使用 for 或 if...如何?

谢谢!

最佳答案

实际上不行,你需要使用运算符“&”的地址来将值存储到数组中。

scanf("%f", &timerunner1[x]);

此外,您的数组不够大,无法存储循环所需的 6 个整数,并且数组的下标从 0 开始,到 5 结束(对于 6 个元素)。

然后,您可以在读取所有值后进行另一个循环来计算最大值,或者按如下方式即时计算:

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

float timerunner1[6];
int x;
float maximum = 0.0f;

int main() {

for (x = 0; x < 6; x++) {
    printf("Give me the time of runner 1: ");
    scanf("%f", &timerunner1[x]);
    maximum = maximum > timerunner1[x] ? maximum : timerunner1[x];
}

printf("%f\n", maximum);

return 0;
}

此外,此代码仅适用于正值,因为最大值初始化为零,并且始终大于任何负值,如果您需要负值,您应该能够进行实验并找出答案。

关于arrays - ANSI C - 数组的较高元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12773650/

相关文章:

java - java中如何将ArrayList中的元素复制到int数组

c - 将数组中的值设置为仅等于 1 或 0

javascript - 从数组中删除特定项目,未按预期工作

c++ - 如何在函数内部操作 char 数组(字符串)的指针,它在 c/c++ 中作为参数传递

c - 为什么 readline 库中的 readline() 不接受 UNICODE? ANSI C语言

awk - shell脚本中增加输入变量号

numbers - Prolog - 对数字求和

arrays - 数组中元素的平均值

c - 函数 : findnextchar() doesn't work

javascript - REACT - 达到小数点后 2 位后防止小数点后输入