如何从数组中打印整行?

时间:2011-01-30 16:32:57

标签: c++

我写了一个程序,显示有关5名学生的数据,我想知道如何显示学生姓名注册号,并标记谁在阵列中获得最高分。 该计划就是这样:

#include "stdio.h"
#include "conio.h"

struct student
{
    char name[30];
    char reg[10];
    short int marks_dbms;
    short int marks_prog;
};

void main()
{
    short int i;

    student a[5]={      
        {"salman","B-1499",92,98},
        {"Haider","B-1489",34,87},
        {"zeeshan","B-1897",87,90},
        {"faizan","B-1237",56,66},
        {"Asif","B-1233",88,83}

    };

    for(i=0; i<5; i++)
    {
        printf("%s\t",a[i].name);
        printf("%s\t",a[i].reg);
        printf("%d\t",a[i].marks_dbms);
        printf("%d\t\n",a[i].marks_prog);

    }

    getch();

}

2 个答案:

答案 0 :(得分:0)

这很简单。


int maxDbmsMarks = 0; 
int maxMarksIndex = 0;
for(int i = 0; i < 5; i++)
{
   if(a[i].marks_dbms > maxDbmsMarks )
   {
        maxDbmsMarks = a[i].marks_dbms;
        maxMarksIndex = i;
   }
}

printf("Student with the maximum dbms marks :\n");
printf("Name : %s, Reg : %s, dbmsMarks: %d, progMarks : %d\n", a[maxMarksIndex].name, a[maxMarksIndex].reg, a[maxMarksIndex].makrs_dbms, a[maxMarksIndex].marks_prog);

与查找数组中的最大数量相同。以上逻辑用于“最高dbms标记”,您可以对其进行修改以找到最高编号或最高组合标记。

答案 1 :(得分:0)

首先,编写一个函数来比较学生的分数。它应该接受两个学生参数,如果第一个学生应该被认为少于第二个学生,则返回true。

bool compareStudentsByMarks(const student & lhs, const student & rhs)
{
    // This only compares by marks_dbms, I'm not sure how you want to do it.
    return lhs.marks_dbms < rhs.marks_dbms;
}

然后,在包含<algorithm>标题后,使用函数std::max_element,将函数作为最后一个参数传递。

const int SIZE_OF_STUDENT_ARRAY = 5;
student * pmax = std::max_element(a, a+SIZE_OF_STUDENT_ARRAY, compareStudentsByMarks);
// now pmax is a pointer to the student with the highest marks,
// you already know how to display their info

如果您可以访问C ++ 0x,那么这就容易多了:

auto pmax = std::max_element(a, a+SIZE_OF_STUDENT_ARRAY,
    [](const student & lhs, const student & rhs)
    {
        return lhs.marks_dbms < rhs.marks_dbms;
    });