【问题标题】:Find Max and Min in an array type struct [closed]在数组类型结构中查找 Max 和 Min [关闭]
【发布时间】:2016-02-22 18:48:52
【问题描述】:

我正在尝试查找数组类型结构的最大值、最小值、平均值和平均值。我有一个函数“bsort”,它使用结构团队中的冒泡排序对我的所有数据进行排序,我在这里称之为对我的数据进行排序。这是我用来查找最大值的代码:

void bfind(struct annual_stats *stats, int y, int year, string field, string item){ 
    bsort(stats, y, year, field, "increasing"); 

    if (item == "max"){
        int max;
     for (int i = 0; i < NO_TEAMS; i++) {

    if (stats->teams->games[i] > max){
            max = stats->teams->games[i];
         }
    }
}    

}

其中 stats 是一个结构,它有两个元素,一个整数和另一个结构:

struct annual_stats{
int year;
struct team_stats teams[ NO_TEAMS ];
};

然后我有这些声明:

#define NO_TEAMS      32 // Number of NFL teams
#define TEAM_NAME_LEN 25 // Maximum team name string length
#define TOP_LEN        6 // Maximum time of possession string length

我的结构团队如下:

 struct team_stats{
char team_name[ TEAM_NAME_LEN ]; // Name of NFL team
int games; // Number of games played in the season
float pts_per_game; // Points per game
int total_points; // Total points
int scrimmage_plays; // Scrimmage plays
float yds_per_game; // Yards per game
float yds_per_play; // Yards per play
float first_per_game; // First downs per game
int third_md; // Third down conversions
int third_att; // Third down attempts
int third_pct; // Third down percentage
int fourth_md; // Fourth down conversions
int fourth_att; // Fourth down attempts
int fourth_pct; // Fourth down percentage
int penalties; // Number of penalties
int pen_yds; // Penalty yards
char top_per_game[ TOP_LEN ]; // Time of possession per game
int fum; // Number of fumbles
int lost; // Fumbles lost
int to; // Turnover ratio
};

然后,teams 是一个数组类型的结构,它包含 20 个 int、float 和 char 类型的元素。 我在这里想要做的是我想找到游戏的最大值,这是团队的 int 成员。当我运行这个程序时,我不断收到一个错误,即数组下标的无效类型 int[int]。 我知道如果我删除 [],我的程序会编译,但我认为我必须指定元素 [i]? 谁能给我一些提示?

我的程序正在从文本文件中读取数据。

顺便说一句,我不是 C++ 专家,所以请以最简单的方式解释! 谢谢。

【问题讨论】:

  • 对于您真正的问题:请发布minimal reproducible example,以便我们诊断问题。
  • 请简述您的问题并与我们分享“bsort”功能。并且 NO_TEAMS 是否在某处声明?,最好在这里准确地提问,因为这对我们帮助你有好处。干杯:)
  • 元评论:你真的做这个C数组/指针/自制排序业务吗?您在第一句话中提到的任务可以使用标准库更高效、更简单地完成。
  • @DanyalImran 我们可能不需要看到bsort 来诊断bfind 中的编译器错误,你不觉得吗?
  • “嗯,这是一个很长的程序,这就是为什么我尽量保持简短” - 您仍然可以发布一个简短的程序来显示您的问题。

标签: c++ for-loop struct max


【解决方案1】:
void bfind(struct annual_stats *stats, int y, int year, string field, string item){ 
    bsort(stats, y, year, field, "increasing"); 

    if (item == "max"){
        int max;
     for (int i = 0; i < NO_TEAMS; i++) {

    if (stats->teams[i].games > max){
            max = stats->teams[i].games;
         }
    }
}

我觉得应该stats-&gt;teams[i].games

【讨论】:

  • @BaummitAugen 你是对的。它必须是 team[i].games。感谢您的帮助!
  • 我刚刚尝试过,是的@BaummitAugen 对,它应该使用点,我会更新我的答案
  • @malioboro 谢谢你的建议。它让我走上了正确的道路。
  • 哦,谢谢,这是我第一次编辑我的答案
  • @malioboro 没问题。为了将来参考,如果您觉得某个编辑需要额外的解释,请在编辑时在编辑摘要中提供。这对于编辑其他人帖子的
猜你喜欢
  • 2020-11-23
  • 2017-06-30
  • 1970-01-01
  • 2021-12-14
  • 2021-05-04
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 2015-02-18
相关资源
最近更新 更多