查找书籍

https://pintia.cn/problem-sets/12/problems/346

这个程序的算法不难,因为没有学透标准输入和输出,特别是gets()函数。如果不用getchar()读取多余的‘\n‘,程序就会运行错误。

#include <stdio.h>
#include <stdlib.h>

struct book
{
    char title[31];
    double price;
};
int main(void)
{
    int i, n, min, max;
    struct book *p;

    scanf("%d", &n);
    p = (struct book *)calloc(n, sizeof(struct book));
   
    for (i = 0; i < n; i++)
    {
        getchar();
        gets((p+i)->title);
        scanf("%lf", &((p+i)->price));
    }
    min = max = 0;
    for (i = 1; i < n; i++)
    {
        if ((p + i)->price > (p + max)->price)
        {
            max = i;
        }
        if ((p + i)->price < (p + min)->price)
        {
            min = i;
        }
    }
    printf("%.2f, %s\n", (p + max)->price, (p + max)->title);
    printf("%.2f, %s\n", (p + min)->price, (p + min)->title);

    free(p);
    return 0;
}

相关推荐