gpt4 book ai didi

c - 出售苹果股票(一进一出)

转载 作者:行者123 更新时间:2023-11-30 18:51:49 25 4
gpt4 key购买 nike

任何人都可以帮我解决我的代码吗,我在卖苹果时遇到问题,它减去我的所有股票,有时当我的输入超过股票时,数字会变成负数

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

一进一出

当我的输入超过库存时,它会显示“缺货!”并且不会继续减少我的库存

最佳答案

第三个选择中的问题如问题评论中所示,正确的代码应该是这样的(它是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();
}

关于c - 出售苹果股票(一进一出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35920230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com