代码无效(C)

时间:2017-04-28 09:42:10

标签: c

我想用struct和数组来计算工资,但它不起作用。当您看到代码时,您将更好地理解练习。出于某种原因,如果在WageDays_Worked中输入一个数字(100和2) Wagered[i].Gross_Wage = Wagered[i].Wage * Wagered[i].Days_Worked;不会给我200但是其他的东西。一般来说,该程序不会起作用,我正试图找到原因。

#include <stdio.h>

struct User
{
    char First_Name[25];
    char Last_Name[25];
    int Wage, Days_Worked;
    int Tax;
    int Wage_Booking;
    int Net_Wage;
    int Gross_Wage;
};

int main()
{
    int i;
    int Wage_Summary = 0;
    struct User Wagered[1];

    for(i = 0; i < 1; i++)
    {
        /*printf("First Name: ");
        scanf("%s", &Wagered[i].First_Name);
        printf("\n");

        printf("Last Name: ");
        scanf("%s", &Wagered[i].Last_Name);
        printf("\n");*/

        printf("Wage: ");
        scanf("%d", &Wagered[i].Wage);
        printf("\n");

        printf("Days He Worked: ");
        scanf("%d", &Wagered[i].Days_Worked);
        printf("\n");

        Wagered[i].Gross_Wage = Wagered[i].Wage * Wagered[i].Days_Worked;
        Wagered[i].Wage_Booking = Wagered[i].Gross_Wage * 0.2;
        Wagered[i].Tax = (Wagered[i].Gross_Wage - Wagered[i].Wage_Booking) * 0.05;
        Wagered[i].Net_Wage = Wagered[i].Gross_Wage - Wagered[i].Wage_Booking - Wagered[i].Tax;
        Wage_Summary += Wagered[i].Net_Wage;
    }

    printf("The Summary of the Gross Wages is: %d\n", Wagered[i].Gross_Wage);

    return 0;
} 

1 个答案:

答案 0 :(得分:2)

本声明:

printf("The Summary of the Gross Wages is: %d\n", Wagered[i].Gross_Wage);

您的for循环。因此,当i具有值1时,它将被执行,因此访问不存在Wagered[1].Gross_Wage的{​​{1}}超出了数组的范围。将其移动到 您的Wagered[1]循环中,如下所示:

for

您将看到打印出的正确结果。