始终读取一个 If-Else 语句

One If-Else statement is always read

我目前的代码有问题,特别是 If-else 部分。如果我的年级为 1,则满足 if-else 但如果我要输入的年级为 2、3 或 4,则满足这些的 if-else 但是,它始终显示 yrep1 的 if-else (它总是打印“年级代表:卡梅尔夫人”)除非年级为 1。

int year, yrep1, yrep2, yrep3, yrep4;

char gov1[] = "Juan Dela Cruz";
...
char fiy1[] = "Lady Carmel";

printf("\nEnter Year Level: ");
scanf("%d", &year);

if(year==1){
    
    printf("\n\n\t\t\t CANDIDATES FOR FIRST YEAR LEVEL REPRESENTATIVE ");
    printf("\n\n1. Lady Carmel");
    printf("\n\n2. Zia Alonzo");
    
    printf("\n\nEnter your vote(Ex. 1): ");
    scanf("%d", &yrep1);

    printf("\nVote has been recorded!");\
    
}else if (year==2){
    
    printf("\n\n\t\t\t CANDIDATES FOR SECOND YEAR LEVEL REPRESENTATIVE ");
    printf("\n\n1. Lita Cordova");
    printf("\n\n2. Mariel Geronimo");
    
    printf("\n\nEnter your vote(Ex. 1): ");
    scanf("%d", &yrep2);
    
    printf("\nVote has been recorded!");
    
}else if (year==3){
    
    printf("\n\n\t\t\t CANDIDATES FOR THIRD YEAR LEVEL REPRESENTATIVE ");
    printf("\n\n1. Carmel De Leon");
    printf("\n\n2. Helen Sy");
    
    printf("\n\nEnter your vote(Ex. 1): ");
    scanf("%d", &yrep3);
    
    printf("\nVote has been recorded!");
    
}else if (year==4){
    
    printf("\n\n\t\t\t CANDIDATES FOR FOURTH YEAR LEVEL REPRESENTATIVE ");
    printf("\n\n1. Stephen Cortes");
    printf("\n\n2. Olivia Yu");
    
    printf("\n\nEnter your vote(Ex. 1): ");
    scanf("%d", &yrep4);
    printf("\nVote has been recorded!");
}

if(yrep1==1){
    printf("\n\n\tYear-level Representative: %s", fiy1);
}else if(yrep1==2){
    printf("\n\n\tYear-level Representative: %s", fiy2);
}

if(yrep2==1){
    printf("\n\n\tYear-level Representative: %s", sy1);
}else if(yrep2==2){
    printf("\n\n\tYear-level Representative: %s", sy2);
}

if(yrep3==1){
    printf("\n\n\tYear-level Representative: %s", ty1);
}else if(yrep3==2){
    printf("\n\n\tYear-level Representative: %s", ty2);
}

if(yrep4==1){
    printf("\n\n\tYear-level Representative: %s", foy1);
}else if(yrep4==2){
    printf("\n\n\tYear-level Representative: %s", foy2);
}
printf("\n\n\t\t\t\t\tBALOT RECEIPT");
printf("\n\n\tNAME: %s", name);
printf("\t\t\t\t\tDATE: %s", ctime(&t));
printf("\n\tYEAR LEVEL: %d", year);
printf("\n\n\tYEAR SECTION: %s", section);
printf("\n\n\t\t\tYOU'VE VOTED FOR THE FOLLOWING CANDIDATES:");

问题是这些变量

int year, yrep1, yrep2, yrep3, yrep4;

未初始化且具有不确定的值。

你需要用零初始化它们。

int year, yrep1 = 0, yrep2 = 0, yrep3 = 0, yrep4 = 0;

另一种方法是将 if-else 语句包含在另一个 if 语句中,例如

if(year==1)
{
    if(yrep1==1){
        printf("\n\n\tYear-level Representative: %s", fiy1);
    }else if(yrep1==2){
       printf("\n\n\tYear-level Representative: %s", fiy2);
    }
}