Declaring variables outside loop/IF structures in C

前端 未结 2 804
名媛妹妹
名媛妹妹 2021-01-25 08:51

I\'m new to the C language, rather programming overall. I was wondering why is it that when I declare a variable to be used within an if statement OUTSIDE the structure, that th

2条回答
  •  别那么骄傲
    2021-01-25 09:17

    Maybe you are trying to eliminate the duplicate code. Since the difference between the if blocks is the tax rate, you could set the rate and at the end make one calculation.

    #include
    void grossPay();
    
    int main()
    {
        grossPay();
    }
    
    void grossPay()
    {
        int rate = 10, hours;
        double tax, grosspay, netpay;
    
        printf("Enter work hours this week: ");
        scanf("%d", &hours);
    
        grosspay = hours * rate;
    
        if (grosspay <= 300 && grosspay > 0)
        {
            tax = 0.10;
        }
        else if (grosspay > 300 && grosspay <=1000)
        {
            tax = 0.15;
        }
        else if (grosspay > 1000)
        {
            tax = 0.25;
        }
        else
        {
            printf("Invalid input. Please try again.\n\n");
            return;
        }
        netpay = grosspay - grosspay * tax;
        printf("Pay for %d hours of week with $%d per hour\n", hours, rate);
        printf("Gross pay: $%.2f\n", grosspay);
        printf("Net pay: $%.2f\n", netpay);
    }
    

提交回复
热议问题