首页 > 解决方案 > C - 访问函数中的变量以在用户退出程序时打印总和

问题描述

所以我正在创建一个在线杂货店,其中每个产品都被分配了一个名称、产品 ID 和价格。每次用户通过输入关联的 id 购买产品时,他们的总支付成本都会更新。

产品和输出示例:

Products:
Name: orange, id: 100, price: 4.50
Name: banana, id: 101, price: 2.00
Name: milk, id: 102, price: 3.00

User presses '3':
User enters: 101
Current price to pay: 2.00

User presses '3':
User enters: 102:
Current price to pay: 5.00

User presses '3':
User enters: 101
Current price to pay: 7.00

User presses '0':
Total price to pay is: $7.00

因此计算并向用户打印当前价格是可行的,但是我无法访问变量“sum”,该变量表示当用户决定通过输入“0”退出时用户必须支付的总价格。我考虑过可能以某种方式返回 sum 变量,甚至创建一个新函数并调用它,但我不确定如何去做,希望能得到一些帮助。正如您在 main.c 中看到的,当用户输入 '0' 时,我添加了一个打印语句 'printf("Total price to pay: $%f \n", sum); ' 但问题是 sum 在这里不存在,所以我无法获得总成本。

附带说明一下,我尝试在 purchaseProd() 中声明和初始化变量 sum,但它实际上不会计算所有产品的总和,而只会输出他们想要专门购买的产品的当前价格。因此,例如,在我上面的输出中,购买产品 id '102' 后当前支付的价格将是 3.00 美元,因为这是产品的价格,即使我希望它打印出 5.00 美元。这是通过在函数外部声明 sum 变量来解决的,使其成为全局变量。

我试图避免声明全局变量,因为有人告诉我这是不好的做法,并且想知道除了将 sum 设为全局变量之外,是否有办法让我的当前价格正确计算?有没有办法可以改为在 main() 中声明它,然后在我实际需要向其中添加不同购买的价格时访问它?

主程序

int main(){
    int choice;
    while(1){
        printf("(1) Print inventory \n");
        printf("(2) Add product stock \n");
        printf("(3) Buy product \n");
        printf("(0) Exit \n");

        printf("Enter choice: ");
        scanf("%d", &choice);
        
        if(choice == 0){
            printf("Total price to pay: $%f \n", sum); //how to access total sum variable?
            exit(0);
        }
        if(choice == 1){
        }
        if(choice == 2){
        }
        if(choice == 3){
            int enterId;
            printf("Product id: ");
            scanf("%d", &enterId);  
            purchaseProd(p, enterId);
        }
    }
    return 0;
}

库存.c

float sum = 0;
int purchaseProd(ProdCollectionType* prodCollection, int getId){
    //int sum = 0;
    for(i = 0; i < prodCollection->numProducts; ++i){
        if(prodCollection->products[i]->id == getId){
            sum += prodCollection->products[i]->price;
            printf("Current price to pay: $%.2f \n", sum);
          }
        }
    }
}

标签: arrayscpointersiteratorsum

解决方案


你要这个:

int main(){
    int choice;
    float sum = 0;    // add this

    while(1){
        ...
        if(choice == 3){
            int enterId;
            printf("Product id: ");
            scanf("%d", &enterId);  
            sum = sum + purchaseProd(p, enterId);   // change here
        }
    }
    return 0;
}

// float sum = 0;                                      // remove this
float purchaseProd(ProdCollectionType* prodCollection, int getId){
    float sum = 0;                                      // add this
    for(i = 0; i < prodCollection->numProducts; ++i){
        if(prodCollection->products[i]->id == getId){
            sum += prodCollection->products[i]->price;
            printf("Current price to pay: $%.2f \n", sum);
          }
        }
    }

   return sum;                                         // add this
}

推荐阅读