gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:33:08 24 4
gpt4 key购买 nike

我是 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/

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