In thông tin của thẻ có số tiền lớn nhất

Mục tiêu của mình là muốn in ra thông tin của thẻ tiết kiệm có số tiền lĩnh lớn nhất. Mình đã tạo hàm gtln() để tìm max và in ra giá trị lớn nhất nhưng lại không in được thông tin của thẻ.

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<math.h>

struct thetk {
    int mathe;
    char tenthe[20];
    float tiengui, laisuat, tienlinh;
    int namgui;
};

void nhap(struct thetk a[], int n){
    int i;
    for (i = 1; i <= n; i++) {
        printf("nhap du lieu the thu %d", i);
        printf("\nma the:");
        scanf("%d", & a[i].mathe);
        fflush(stdin);
        printf("\nten the:");
        gets(a[i].tenthe);
        printf("\nlaisuat:");
        scanf("%f", & a[i].laisuat);
        printf("\ntien gui:");
        scanf("%f", & a[i].tiengui);
        printf("\nnam gui:");
        scanf("%d", & a[i].namgui);
    }
}

void tinh(struct thetk a[], int n) {
    int i, x;

    for (i = 1; i <= n; i++) {
        x = 2019 - a[i].namgui;
        a[i].tienlinh = pow(a[i].laisuat + 1, x) * a[i].tiengui;
    }
}

void gtln(struct thetk a[], int n) {
    int i;
    float max;
    max = a[1].tienlinh;
    for (i = 2; i <= n; i++)
        if (max < a[i].tienlinh)
            max = a[i].tienlinh;
    printf("\n max:%.2f", max);
    printf("\n ten the:%s", a[i].tenthe);
}
void xuat(struct thetk a[], int n) {
    int i;

    printf("\n| ma the | ten the | nam gui | tien linh |");
    printf("\n------------------------------------");
    for (i = 1; i <= n; i++) {
        printf("\n|%-8d|%-9s|%-9d|%-10.2f|", a[i].mathe, a[i].tenthe, a[i].namgui, a[i].tienlinh);
        printf("\n------------------------------------");
    }
}

main() {
        int i, n;
        printf("\nnhap so the:");
        scanf("%d", & n);
        struct thetk b[20];
        nhap(b, n);
        tinh(b, n);
        xuat(b, n);
        gtln(b, n);
        xuat(b, n);
}

i lúc này sẽ bằng n+1 mà bạn cần xuất của max chứ có phải của n+1 đâu. :slight_smile:

Sửa lại thành như này:

void gtln(struct thetk a[], int n) {
    int iom = 1; // index of max
    for (int i = 2; i <= n; i++)
        if (a[iom].tenlinh < a[i].tienlinh)
            iom = i;
    printf("\n max:%.2f", a[iom].tienlinh);
    printf("\n ten the:%s", a[iom].tenthe);
}

Còn nữa, mảng trong C bắt đầu từ 0 chứ không phải 1. :slight_smile:
int a[n] thì là chạy từ a[0] cho đến a[n-1].

4 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?