我的代码在获取 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/