嘣叽 2026-03-17 01:26 采纳率: 60%
浏览 12

为何n最小结果不对C语言?

#查找书籍
给定n本书的名称和定价,本题要求编写程序,查找并输出其中定价最高和最低的书的名称和定价。

##输入格式:
输入第一行给出正整数n(<10),随后给出n本书的信息。每本书在一行中给出书名,即长度不超过30的字符串,随后一行中给出正实数价格。题目保证没有同样价格的书。

##输出格式:
在一行中按照“价格, 书名”的格式先后输出价格最高和最低的书。价格保留2位小数。

##输入样例:
3
Programming in C
21.5
Programming in VB
18.5
Programming in Delphi
25.0
##输出样例:
25.00, Programming in Delphi
18.50, Programming in VB

#include <stdio.h>

typedef struct book{
    char name[31];
    float price;
};

int main(){
    int n;
    scanf("%d", &n);
    struct book books[n];
    for(int i = 0; i < n; i++){
        int j = 0;
        char c;
        scanf("%c", &c);
        while(scanf("%c", &c) == 1 && c != '\n'){
            books[i].name[j] = c;
            j++;
        }
        books[i].name[j] = '\0';
        scanf("%f", &books[i].price);
        //printf("%s %f\n", books[i].name, books[i].price);
    }
    if(n == 1){
        printf("%.2f, %s\n", books[0].price, books[0].name);
        return 0;
    }
    int max = 0, min = 0;
    for(int i = 0; i < n; i++){
        if(books[i].price > books[max].price){
            max = i;
        }
        if(books[i].price < books[min].price){
            min = i;
        }
    }
    printf("%.2f, %s\n%.2f, %s", books[max].price, books[max].name, books[min].price, books[min].name);
    return 0;
}

img

  • 写回答

4条回答 默认 最新

  • a5156520 2026-03-17 10:20
    关注

    把第24行到第27行去掉试试,因为当只有一本书籍时,最贵的书籍与最便宜的书籍是同一本。

    修改如下:

    #include <stdio.h>
     
    typedef struct book{
        char name[31];
        float price;
    };
     
    int main(){
        int n;
        scanf("%d", &n);
        struct book books[n];
        for(int i = 0; i < n; i++){
            int j = 0;
            char c;
            scanf("%c", &c);
            while(scanf("%c", &c) == 1 && c != '\n'){
                books[i].name[j] = c;
                j++;
            }
            books[i].name[j] = '\0';
            scanf("%f", &books[i].price);
            //printf("%s %f\n", books[i].name, books[i].price);
        }
        // 去掉这个if试试,因为当只有一本书籍时,最贵的书籍与最便宜的书籍是同一本 
    //    if(n == 1){
    //        printf("%.2f, %s\n", books[0].price, books[0].name);
    //        return 0;
    //    }
        int max = 0, min = 0;
        for(int i = 0; i < n; i++){
            if(books[i].price > books[max].price){
                max = i;
            }
            if(books[i].price < books[min].price){
                min = i;
            }
        }
        printf("%.2f, %s\n%.2f, %s", books[max].price, books[max].name, books[min].price, books[min].name);
        return 0;
    }
     
    
    

    img

    评论

报告相同问题?

问题事件

  • 修改了问题 3月17日
  • 创建了问题 3月17日