C 把收获的苹果储存起来

C 把收获的苹果储存起来,c,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);

谁能帮我把每天收获的苹果储存起来,收获后每天增加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

您应该将
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;    
}
#包括
无效显示菜单(无效){
printf(“1.harvest\n”);
printf(“2.查看库存\n”);
printf(“\n选择:”);
}
int main(void){
int-choice=0;
整数苹果=0,天数=1;
int stocks[100]={0};
对于(;;){
clrsc();
printf(“天%d\n”,天);
dispMenu();
如果(scanf(“%d”,&choice)!=1)
打破
如果(选项==1&&days<100){
printf(“输入收获的苹果数量:”);
scanf(“%d”)和股票[天数];
天++;
}
如果(选项==2){
printf(“日股”);
对于(int i=1;i
你需要将苹果的数量存储在一个数组中。现在你只需将
apples
变量复制到
stocks
变量中,这是无用的。你应该学习的概念:循环和数组。@Michael Walz我应该使用什么循环,这取决于你。但是当你需要显示从索引0到days-1的数组时,a
for
循环是最方便的。不要使用
goto
为此,一个简单的循环更好。如何对股票进行细分1 200 2 150 3350@iCe_Star:我用
股票的数组更新了上面的代码。