数组不能正确使用C中的函数?

数组不能正确使用C中的函数?,c,arrays,function,C,Arrays,Function,我正在为一个大学研讨会制定一个计划。我几乎完成了,但当我编译并运行程序时,它并没有按照预期的方式工作: 这是我的密码: #include <stdio.h> int calulation(long long int barcode[100], double price[100], int quantity[100], int i); int main(void) { long long int barcode[100]; double price[100];

我正在为一个大学研讨会制定一个计划。我几乎完成了,但当我编译并运行程序时,它并没有按照预期的方式工作: 这是我的密码:

#include <stdio.h>

int calulation(long long int barcode[100], double price[100], int quantity[100], int i);

int main(void) {
    long long int barcode[100];
    double price[100];
    int quantity[100];
    int i;

    printf("Grocery Store Inventory \n");
    printf("======================= \n");

    printf("Barcode: ");
    scanf("%lld", &barcode[0]);
    printf("Price: ");
    scanf("%f", &price[0]);
    printf("Quantity: ");
    scanf("%d", &quantity[0]);


    for (i = 0;i < 99; i++) {

        printf("Barcode: ");
        scanf("%lld", &barcode[i]);
        if (barcode[i] == 0) {
            break;
        }
        printf("Price: ");
        scanf("%f", &price[i]);
        printf("Quantity: ");
        scanf("%d", &quantity[i]);

    }
    calculation(barcode, price, quantity, i);
}

int calculation(long long int barcode[], double price[], int quantity[], int i) {

    double totalAmount;
    int j;

    printf("Goods in Stock \n");
    printf("===============\n");

    //j count and display entered value as long as it is less than i

    for (j=0;j<i+1;j++) {

        printf(" %lld, %.2f, %d, %.2f  \n", barcode[j], price[j], quantity[j]);
    }

    //All prices are added for totalamount
    for(j = 0; j < i+1; j++) {

        totalAmount = price[j] + price[j];
    }

    //totalamount is multiplied by quantity for the final price
    for (j = 0; j < i+1; j++) {

        totalAmount = totalAmount * quantity[j];
    }

    printf("Total value goods in stock: %.2f \n", totalAmount);
}

我们输入条形码、价格和数量,当条形码为0时,程序结束。

price
double
的数组。你应使用:

scanf("%lf", &price[0]);
在这一行

printf(" %lld, %.2f, %d, %.2f  \n", barcode[j], price[j], quantity[j]);

您有4个标识符,但只有3个变量。

您有两组三个scanf()调用,一次用于索引0,然后又是99次,从索引0开始。因此,您输入的第一组数据总是被第二组数据覆盖

printf("Quantity: ");
scanf("%d", &quantity[0]);

for (i = 1; i < 99; i++) {

    printf("Barcode: ");
    scanf("%lld", &barcode[i]);
在值为0的条形码上,用i结束
for
循环,因此有效值为i-1:

 printf(" %lld, %.2f, %d  \n", barcode[j], price[j], quantity[j]);
您想打印4个vlaues,但为什么需要3个vlaues:

for( j = 0; j < i+1; j++) {

    totalAmount = totalAmount + (price[j]*quantity[j]);
}
(j=0;j{ 合计金额=合计金额+(价格[j]*数量[j]); } 可能您希望将一种类型的对象的数量相乘

  • “scanf(“%f”,&price[0])”
    价格是一系列的双倍。您应该将%lf与scanf一起使用

  • for
    循环中,覆盖条形码[0]、数量[0]、价格[0]

  • 在计算函数中,在第一个循环中不需要最后的%.2f,因为只有三个变量。这就是你得到-0.00的原因

  • 在计算函数的第二个
    for
    循环中,将产品的价格相加并乘以2

  • 然后在第三个
    for
    循环中,将所有产品的总价乘以每个产品的数量。这毫无意义

    您可能想这样做:

    double sum = 0;
    
    将此行放入第二个
    for
    循环,并删除第三个
    for
    循环:

    sum += price[j]*quantity[j];
    
    double sum = 0;
    
    sum += price[j]*quantity[j];