有人可以帮我每天将收获的苹果存储到库存中吗,收获增加一天后,每天只能收获一次。
到目前为止,这是我的代码
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;
}