将收获的苹果储存到库存中

时间:2016-03-08 13:40:52

标签: c

任何人都可以帮助我将每天收获的苹果储存到库存中,收获后每天增加1个,每天只收获一个。

到目前为止,这是我的代码

void dispMenu();

int main() {        
    int choice = 0;
    int apple = 0, stocks, days = 1;

menu:
    clrscr();
    printf("Day %d\n", days++);
    dispMenu();

    scanf("%d", &choice);  

    if (choice == 1) {    
        printf("Enter Number of apples harvested: ");
        scanf("%d", &apple);        
    }

    stocks = apple;

    if (choice == 2) {    
        printf("Day    Stocks\n");
        printf("%2d     %4d\n", days, stocks);      
    }
    getch();
    goto menu;    
}

void dispMenu() {       
    printf("1. harvest\n");
    printf("2. View Stocks\n");
    printf("\nchoice: ");
}

例如:

Day 1 I input in harvest is 200
Day 2 I input in harvest is 150
Day 3 I input in harvest is 350
...days are infinite

查看库存时应显示

 DAY   STOCKS
  1     200
  2     150
  3     350

1 个答案:

答案 0 :(得分:0)

您应该将stocks初始化为0并将其增加收取的金额,而不是仅仅设置它。为了保持每天一行的列表,您需要一个数组。

您还应该用循环替换goto

#include <stdio.h>

void dispMenu(void) {       
    printf("1. harvest\n");
    printf("2. View Stocks\n");
    printf("\nchoice: ");
}

int main(void) {        
    int choice = 0;
    int apple = 0, days = 1;
    int stocks[100] = { 0 };

    for (;;) {
        clrscr();
        printf("Day %d\n", days);
        dispMenu();

        if (scanf("%d", &choice) != 1)
            break;

        if (choice == 1 && days < 100) {    
            printf("Enter Number of apples harvested: ");
            scanf("%d", &stocks[days]);
            days++;
        }
        if (choice == 2) {    
            printf("Day    Stocks\n");
            for (int i = 1; i < days; i++) {
                printf("%2d     %4d\n", i, stocks[i]);      
        }
        getch();
    }
    return 0;    
}