#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define START_CASH 1000
#define ROUNDS 20
#define MIN_PRICE 1
#define MAX_PRICE 10
#define MIN_SHARES 1
#define MAX_SHARES 100
const char *COMPANIES[] = {
"腾讯", "阿里", "字节", "华为",
"美团", "京东", "百度", "小米"
};
const int NUM_COMPANIES = sizeof(COMPANIES) / sizeof(COMPANIES[0]);
int main() {
srand(time(NULL));
int cash = START_CASH;
int round_count = 0;
char play_again;
printf("===== 股票投资模拟器 =====\n");
printf("初始资金: %d元\n\n", START_CASH);
do {
const char *company = COMPANIES[rand() % NUM_COMPANIES];
int price = rand() % (MAX_PRICE - MIN_PRICE + 1) + MIN_PRICE;
int shares_held = 0;
printf("===== 第 %d 局开始 =====\n", ++round_count);
printf("公司: %s\n", company);
printf("当前股价: %d元\n\n", price);
for (int round = 1; round <= ROUNDS; round++) {
int change = (rand() % 3) - 1;
price += change;
if (price < MIN_PRICE) price = MIN_PRICE;
if (price > MAX_PRICE) price = MAX_PRICE;
printf("--- 回合 %d ---\n", round);
printf("当前股价: %d元 (%+d元)\n", price, change);
printf("你的现金: %d元\n", cash);
printf("持有股数: %d\n", shares_held);
char action;
int shares_to_trade;
int valid = 0;
while (!valid) {
printf("\n操作: (B)买进 (S)卖出 (P)跳过: ");
scanf(" %c", &action);
action = toupper(action);
if (action == 'P') {
valid = 1;
printf("跳过本回合\n");
} else if (action == 'B' || action == 'S') {
printf("交易股数 (%d-%d): ", MIN_SHARES, MAX_SHARES);
if (scanf("%d", &shares_to_trade) != 1) {
printf("输入无效!\n");
while (getchar() != '\n');
continue;
}
if (shares_to_trade < MIN_SHARES || shares_to_trade > MAX_SHARES) {
printf("股数范围 %d-%d!\n", MIN_SHARES, MAX_SHARES);
continue;
}
int cost = shares_to_trade * price;
if (action == 'B') {
if (cost > cash) {
printf("现金不足!需要%d元,只有%d元\n", cost, cash);
} else {
cash -= cost;
shares_held += shares_to_trade;
printf("买入 %d 股,花费 %d元\n", shares_to_trade, cost);
valid = 1;
}
} else {
if (shares_to_trade > shares_held) {
printf("持股不足!只有%d股\n", shares_held);
} else {
cash += cost;
shares_held -= shares_to_trade;
printf("卖出 %d 股,获得 %d元\n", shares_to_trade, cost);
valid = 1;
}
}
} else {
printf("无效操作!请选择 B/S/P\n");
}
}
printf("------------------------\n\n");
}
int final_value = cash + shares_held * price;
printf("===== 第 %d 局结算 =====\n", round_count);
printf("最终股价: %d元\n", price);
printf("剩余持股: %d股 (价值 %d元)\n", shares_held, shares_held * price);
printf("现金: %d元\n", cash);
printf("总资产: %d元\n", final_value);
printf("本局收益: %d元\n\n", final_value - START_CASH);
cash = final_value;
printf("开始下一局? (Y/N): ");
scanf(" %c", &play_again);
play_again = toupper(play_again);
printf("\n");
} while (play_again == 'Y');
printf("游戏结束!最终资产: %d元\n", cash);
return 0;
}