以下是发生的事情:我给变量“pay”一个值。例如16。我使用printf打印付款,然后我回来了16。然后我再次打印,然后得到0.如果我第三次打印它,我再次打16。
此外,无论我做什么,我似乎总是为员工类型获得0。
感谢任何帮助。谢谢!
#include<stdlib.h>
#include<stdio.h>
int main(void)
{
float pay;
int employees;
int type;
int hours;
int items;
int i;
int j;
printf("How many employees? ");
scanf("%d", &employees);
float array[employees][2];
for(i = 0; i < employees; i++)
{
printf("\nWhat type of employee is employee #%d?", i + 1);
printf("\nEnter \"1\" for Manager.\nEnter \"2\" for Hourly Worker.\nEnter \"3\" for Commission Worker.\nEnter \"4\" for Pieceworker.");
scanf("%d", &type);
switch (type)
{
case 1:
array[i][0] = 1;
printf("\nWhat is the weekly pay for employee #%d (manager)?", i + 1);
scanf("%f", &pay);
array[i][1] = pay;
printf("\nEmployee #%d earned $%.2f this week.", i + 1, array[i][1]);
break;
case 2:
array[i][0] = 2;
printf("\nWhat is the hourly pay for employee #%d (Hourly Worker)?", i + 1);
scanf("%f", &pay);
printf("\nHow many hours did employee #%d work this week?", i + 1);
scanf("%d", &hours);
if (hours > 40)
{
pay = ((hours - 40) * pay * 1.5) + (hours * pay);
}
else
pay *= hours;
array[i][1] = pay;
printf("\nEmployee #%d earned $%.2f this week.", i + 1, array[i][1]);
break;
case 3:
array[i][0] = 3;
printf("\nWhat were the gross sales for employee #%d (Commission Worker)?", i + 1);
scanf("%f", &pay);
pay = (pay *.057) + 250;
array[i][1] = pay;
printf("\nEmployee #%d earned $%.2f this week.", i + 1, array[i][1]);
break;
case 4:
array[i][0] = 4;
printf("\nHow many items did employee #%d (Pieceworker) produce this week?", i + 1);
scanf("%d", &items);
printf("\nHow much does employee #%d get paid for every item they produce?", i + 1);
scanf("%f", &pay);
pay *= items;
array[i][1] = pay;
printf("\nEmployee #%d earned $%.2f this week.", i + 1, array[i][1]);
break;
}
array[i][0] = type;
printf("\n\nEmployee type: %d", array[i][0]);
printf("\nEmployee #%d earned $%.2f this week.", i + 1, array[i][1]);
}
printf("\n\nEmployee # | Employee Type | Weekly Pay");
for(j = 0; j < employees; j++)
{
printf("\n%10d | %13d | $%.2f", j + 1, array[j][0], array[j][1]);
}
}
编辑:现在我可以获得付费打印的价值。但是,当我尝试打印员工类型时,我仍然得到0。
此外,打印图表的最终循环仍在两个值上返回0。有任何想法吗? (以上代码更新)
答案 0 :(得分:3)
float array[employees - 1][2];
:
for(i = 0; i < employees; i++)
:
blah blah blah ... array[i][2] ...
您正在数组范围之外访问。
当您定义array[42]
之类的内容时,数组元素会按值0
到41
进行索引。 C使用从零开始的索引。
你似乎超越了两个维度的界限,首先使用employees - 1
创建第一个维度,然后使用2
作为第二个维度的索引,尽管事实上你应该只是使用0
和1
。
在尝试解决任何其他问题之前,我先解决这个未定义的行为。
答案 1 :(得分:0)
似乎是数组索引是错误的,它从0开始,但你已经使用了1和2