c - C 数组中的最小值、最大值和位置

标签 c arrays cs50

我是 C 的新手,如果我的怀疑看起来很愚蠢但我被卡住了,请理解。我进行了很多搜索,但找不到解决我的问题的答案。

我的程序应该询问用户比赛的圈数,然后询问每圈花费的时间。

然后写出最快、最慢、单圈平均时间和比赛总时间。现在,总时间和平均值正在发挥作用。最小值和最大值及其位置不是。

这是我的代码:

#include<stdio.h>
#include<cs50.h>

int main()
{
int array[100], maximum, minimum, c, laps, location = 1;
float average;
int summation;

 printf("how many laps did the race had?\n");
 laps = GetInt();
 printf("how many time each of the %i laps took in seconds?\n", laps);

 for (c = 0; c < laps; c++)
 {
      scanf("%d", &array[c]);
      maximum = array[0];
      minimum = array[0];
 }
 for ( c = 1; c < laps; c++)
 {
      if (array[c] < minimum)
      {
          minimum = array[c];
          location = c + 1;
       }
       else if (array[c] > maximum)
       {
           maximum = array[c];
           location = c + 1;
       }
 for ( c = 0; c < laps; c++)
 {
      summation = summation + array[c];
      average = (summation / laps);
 }
 }

printf("The fastest lap was %d and had the time of %d seconds.\n", location, minimum);
printf("The slowest lap was %d and had the time of %d seconds.\n", location, maximum);
printf("The race took %d seconds\n", summation);
printf("The avegare time for lap was %.2f seconds.\n", average);

}

最佳答案

for ( c = 0; c < laps; c++)
 {
      summation = summation + array[c];
      average = (summation / laps);
 }

应该是

int summation = 0;
for ( c = 0; c < laps; c++)
 {
      summation = summation + array[c];
 }
 average = (summation / laps);

因为在知道总和之前计算平均值是没有用的


您对最小和最大位置使用相同的location。使用 minLocationmaxLocation 代替


你有一个括号问题:

for ( c = 1; c < laps; c++)
 {
      if (array[c] < minimum)
      {
          minimum = array[c];
          location = c + 1;
       }
       else if (array[c] > maximum)
       {
           maximum = array[c];
           location = c + 1;
       }
 for ( c = 0; c < laps; c++)
 {
      summation = summation + array[c];
      average = (summation / laps);
 }
 }

应该是

 for ( c = 1; c < laps; c++)
 {
      if (array[c] < minimum)
      {
          minimum = array[c];
          location = c + 1;
       }
       else if (array[c] > maximum)
       {
           maximum = array[c];
           location = c + 1;
       }
}
 for ( c = 0; c < laps; c++)
 {
      summation = summation + array[c];
      average = (summation / laps);
 }

关于c - C 数组中的最小值、最大值和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29408343/

相关文章:

c - 这是整数提升吗?它是如何工作的?

java - 运行时指定的数组/ArrayList 的维数

java - 具有自定义行和列的二维数组

c - 我的代码中的循环哪里出错了?

c++ - 接受指针参数的 GCC 纯/常量函数

c - 我假设下面的 C 代码做了一些事情。但它没有按照我的假设工作。请检查我的假设有什么问题?

c - 检查字符串是否是c中的数字时出现问题

c - 为什么我的strcasecmp函数会带来错误消息? (C)

C - 使用 sscanf 读取多个整数和 float

Javascript,数组