卖苹果股票(1st In 1st Out)

时间:2016-03-10 15:08:03

标签: c

任何人都可以帮我处理我的代码,我卖苹果时遇到问题, 它减去了我所有的股票和当我的输入超过股票

时,有时数字会变为负数
int main(void){

int choice = 0;
int days = 1, i, buyApple;
int stocks[99] = {0};

for (;;){

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

    printf("1. harvest\n");
    printf("2. View Stocks\n");
    printf("3. Sell\n");
    printf("\nchoice: ");

    scanf("%d", &choice);

    if (choice == 1){

        clrscr();
        printf("Input No. of Apple harvested: ");
        scanf("%d", &stocks[days]);
        days++;
    }
    if (choice == 2){

        clrscr();
        printf("Day    Stocks\n");

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

            printf("%2d     %4d\n", i, stocks[i]);      
    }
     getch();

    }
    if(choice == 3){

        printf("Input No. of Appple to be sold: ");
        scanf("%d", &buyApple);

        for (i = 0; i < buyApple; i++){
          stocks[i] = stocks[i] - buyApple;

    }
    if(stocks[i] > buyApple)

        printf("Out of Stocks!");

        getch();    
    }

}
}

期待输出:

例如我的股票就是这个

  Day    Stocks
     1      100
     2       50
     3       50
     4      180
     5      200

如果我输入要销售的苹果是200

我的股票会变成这样的

Day    Stocks
  1        0
  2        0
  3        0
  4      180
  5      200

第一名出局

当我的输入超过股票时,它会说"Out of Stocks !"并且它不会继续减少我的股票

1 个答案:

答案 0 :(得分:2)

问题评论中的第三选择问题,正确的代码应该是这样的(它的c#):

if (choice == 3)
{

    printf("Input No. of Appple to be sold: ");
    scanf("%d", &buyApple);


    for (i = 1; i < sizeof(stocks); i++) //Looping on all stocks you have
    {
        if (buyApple <= stocks[i]) //if amount of apple less than stock apples ,then remove them from stock
        {
            stocks[i] = stocks[i] - buyApple;
            buyApple = 0;
            break;

        }
        else //if amount of apple is bigger than stock apples
        {
            if ((sizeof(stocks) - 1) == i){ //if it's the Last stock,then there is no apples in stock
                printf("Out of Stocks!");
            }
            else //take amount of apples from current stock 
            {
                buyApple = buyApple - stocks[i];
                stocks[i] = 0;
            }
        }

    }

    getch();
}
相关问题