2302_80274807 2023-12-18 08:39 采纳率: 36.4%
浏览 8
已结题

关于#c语言#的问题:为什么程序最多执行两次#include <stdio.h>

为什么程序最多执行两次

#include<stdio.h>
#include<time.h>
#include<stdbool.h>
#include<stdlib.h>
bool play_game(void);
int roll_dice(void);
int main() {
    int n = 0,b=0;
    char a;
    while(true) {
        srand((unsigned)time(NULL));
        if (play_game()) {
            printf("You win\n");
            n++;
        }
        else {
            printf("You lose\n");
            b++;
        }
        printf("Play again?");
        if ((a=getchar())!= 'y') 
            break;
    } 
    printf("Wins:%d Losses:%d\n", n, b);
    return 0;
}
int roll_dice(void) {
    int c, B;
    c = rand() % 6+1;
    B = rand() % 6+1;
    return c + B;
}
bool play_game(void) {
    int d;
    d = roll_dice();
    printf("You rolled:%d\n", d);
    if (d == 7 || d == 11)
        return true;
    if (d == 2 ||d == 3 || d == 12)
        return false;
    printf("Your point is %d\n",d);
    for (;;) {
        int e = roll_dice();
        if (e == d) {
            printf("You rolled: %d\n",d);
            return true;
        }
        if (e == 7) {
            printf("You rolled:%d\n",e);
            return false;
        }
        printf("You rolled:%d\n",e);
    }
}

img

  • 写回答

2条回答 默认 最新

  • we will rise. 2023-12-18 08:47
    关注

    getchar,你输入y然后回车,缓存区里存了y和回车,读取一个y,然后下一次直接读取回车,回车不等于y,可能是这个原因直接就跳出来了,你在最后一个判断break前再加一个getchar,清空缓存区试一下。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 12月26日
  • 已采纳回答 12月18日
  • 创建了问题 12月18日