首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C語言計算平均工資邏輯錯誤:缺少賦值語句與條件判斷冗余

     編輯:程式設計綜合問答

錯誤代碼

int a,b,c,salary;
scanf("%d%d%d",&a,&b,&c);
printf("(a+b+c)/3=%d\n",salary); // 錯誤:salary未賦值,輸出垃圾值
if(a>salary) { ... }
else if(b>salary) { ... } // 錯誤:else if導致只判斷第一個滿足條件的

兩大核心錯誤

  1. 缺少計算賦值:salary = (a + b + c) / 3;必須在printf前執行。
  2. 條件判斷邏輯錯:用else if串聯導致「若a>平均則不再判斷b,c」。需改為獨立if:
if (a > salary) printf("%d\n", a);
if (b > salary) printf("%d\n", b);
if (c > salary) printf("%d\n", c);
if (a <= salary && b <= salary && c <= salary) 
    printf("未達到平均工資\n");

修正後完整代碼

#include 
int main() {
    int a, b, c, salary;
    printf("請輸入三名員工工資: ");
    scanf("%d %d %d", &a, &b, &c);
    
    salary = (a + b + c) / 3; // 關鍵賦值
    printf("平均工資: %d\n", salary);
    
    int count = 0;
    if (a > salary) { printf("%d\n", a); count++; }
    if (b > salary) { printf("%d\n", b); count++; }
    if (c > salary) { printf("%d\n", c); count++; }
    if (count == 0) printf("未達到平均工資\n");
    
    // 題目要求:再輸入一員工工資判斷
    int newEmp;
    printf("請輸入新員工工資: ");
    scanf("%d", &newEmp);
    if (newEmp >= salary) 
        printf("新員工工資 %d 滿足平均工資\n", newEmp);
    else 
        printf("未達到平均工資\n");
    return 0;
}

避坑提醒

  • 變量使用前**必須初始化/賦值**
  • 多條件獨立判斷用**獨立if**,互斥才用else if
  • 整數除法截斷小數,如需精確可用float salary = (a+b+c)/3.0f
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved