首页 > 解决方案 > 循环只取第一个数组值

问题描述

这是我的代码 / giatien 是价格 / soluong 是数量 / dien thoai 是手机

void dienthoai(){
    int soluong,i;
    float giatien[10];
    printf ("Moi nhap so luong dien thoai : "); //please enter how many phone
    fflush(stdin);
    scanf("%d", &soluong);
    
    for (i=0; i<soluong; i++){
        printf("Moi nhap gia tien dien thoai[%d]: ", i); //please enter the price
        scanf("%f",&giatien[i]);
    }
    printf("\n So luong dien thoai: %d", soluong);
    for ( i=0;i<soluong; i++){
    if(giatien[i]>2000000){
    printf("\n Dien thoai co gia tien >=2000000 : %.2f",giatien[i]);
}
}

    int  max = giatien[0];
    for ( i = 1; i < soluong; i++){

        if (giatien[i]> max)
            giatien[i]=max;
}
    printf("\n Dien thoai dat tien nhat la: %d",max); //The most expensive mobile phone is....

}

我试图让控制台返回价格最贵的手机,但不知何故它返回数组中的第一个值

以防我的英语不好

加天[0]:1加天[1]:3000000

控制台显示 giatien[0] 是最昂贵的手机,有人可以帮帮我吗?

标签: c

解决方案


for ( i = 1; i < soluong; i++){
    if (giatien[i]> max){
        //giatien[i]=max; //This is wrong, it should be the other way around
        max = giatien[i]; //This way
    }
}

推荐阅读