gpt4 book ai didi

打印时 C 变量丢失值

转载 作者:太空宇宙 更新时间:2023-11-04 07:20:38 31 4
gpt4 key购买 nike

事情是这样的:我给变量“pay”一个值。例如 16。我使用 printf 打印 pay,然后得到 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]);
}

}

编辑:现在我可以打印 pay 值了。但是,当我尝试打印员工类型时,我仍然得到 0。

另外,打印图表的最后一个循环仍然在两个值上返回 0。有任何想法吗? (上面的代码已更新)

最佳答案

float array[employees - 1][2];
:
for(i = 0; i < employees; i++)
:
blah blah blah ... array[i][2] ...

您正在访问数组范围之外。

当您定义诸如 array[42] 之类的内容时,数组元素由值 041(含)进行索引。 C 使用从零开始的索引。

您似乎在两个维度上都越界了,首先是使用 employees - 1 创建第一个维度,其次是使用 2 作为第二个维度的索引尽管事实上您应该只使用 01

在尝试解决任何其他问题之前,我会先修复未定义的行为。

关于打印时 C 变量丢失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21872013/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com