scanf未正确读取选择值,循环始终重复执行print_menu()问题求助
问题分析与修复方案
核心错误:变量赋值顺序颠倒
你代码里的这行完全搞反了:
choice = choice1;
这行是把choice1的值赋给choice,但你实际需要的是把用户输入的choice赋值给choice1,这样后续的if(choice1 == 1)判断才能拿到正确的输入值。正确写法应该是:
choice1 = choice;
这是导致程序始终重复打印菜单、无法进入分支的直接原因——choice1的值从未被更新为用户输入的数字,自然永远触发不了choice1 == 1的条件。
其他潜在死循环问题
空循环体导致死锁:
while (hands<10);末尾的分号让这个循环变成了空循环,只要
hands小于10,程序就会一直卡在这行不动,永远执行不到后面的发牌逻辑。如果这是要等待hands增长到10,要么去掉分号并在循环体内写更新hands的逻辑,要么直接改成if(hands <10)(如果只是判断一次的话)。无终止条件的循环:
while (ans > 3) { print_hand(face, suit, p1_hand); }当用户输入
ans=1时,这个循环的条件ans>3不成立,根本不会执行;但如果ans不小心大于3,循环体里没有任何修改ans的代码,会一直重复打印手牌,陷入死循环。
修复后的核心代码片段
while (run_game==TRUE) { print_menu(); scanf("%d", &choice); // 修正赋值顺序 choice1 = choice; if (choice1 == 1) { // 去掉空循环的分号,补充hands更新逻辑(示例) while (hands < 10) { // 这里需要写增加hands的代码,比如hands++或者其他业务逻辑 hands++; } shuffle(card_deck); deal(card_deck, face, suit); print_hand(face, suit, p1_hand); printf("You have these cards in your hand:\n"); p1_score = check_hand(p1_hand); p2_score = check_hand(p2_hand); printf("Player one has :%d points\n", p1_score); printf("Redraw card?\n 1.Yes, 2. No\n"); scanf("%d", &ans); if (ans == 1) { // 重新设计红牌逻辑,比如限制重抽次数,同时更新循环条件变量 int redraw_count = 0; while (redraw_count < 3) { print_hand(face, suit, p1_hand); // 这里写重抽卡牌的逻辑 redraw_count++; } } } }
内容的提问来源于stack exchange,提问作者MoeSonOfJoe
相关产品推荐
相关产品推荐

