对于上下文,我正在尝试编写解决C中this problem的代码。
问题相对简单。第一个输入是一个整数,表示分数流中的分数。以下输入是表示分数的所有整数。该程序应通读分数流并返回两个值:最佳分数记录被破坏的次数,以及最差分数记录被破坏的次数。
我写下了这个解决方案。
#include <stdio.h>
int getRecord(int n, int s[], int *max_records, int *min_records)
{
int max_score, min_score;
max_score = min_score = s[0];
for (int i = 1; i < n; i++)
{
if (s[i] > max_score)
{
(*max_records)++;
max_score = s[i];
}
if (s[i] < min_score)
{
(*min_records)++;
min_score = s[i];
}
printf("%d %d\n", max_score, min_score); // inserted to see values
return 0;
}
}
int main(char args[])
{
int n;
scanf("%d", &n);
int s[n];
for (int i = 0; i < n; i++)
scanf("%d", &s[i]);
int max_records = 0;
int min_records = 0;
getRecord(n, s, &max_records, &min_records);
printf("%d %d\n", max_records, min_records);
}
出于某种原因,无论我使用什么输入,for循环在该程序运行时只迭代一次。
答案 0 :(得分:5)
你的循环中有return 0
。
将其更改为:
for (int i = 1; i < n; i++)
{
if (s[i] > max_score)
{
(*max_records)++;
max_score = s[i];
}
if (s[i] < min_score)
{
(*min_records)++;
min_score = s[i];
}
printf("%d %d\n", max_score, min_score); // inserted to see values
}
return 0;