在 C 中添加和打印多个字符

Add and print multiple char in C

我正在创建一个骰子游戏,用户掷 3 个骰子并获得一些随机输出(最多为整数 6)。我的下一步是将获得的这 3 个值相加并得出其总和。 我如何实现这一目标?任何建议都会有所帮助。

这是我的源代码:

//Roll-a-dice Game!
int main(){
    char input1;
    char input2;
    char input3;
    int i;
    int diceRoll;
    int sumDice = (int)(input1-'0') + (int)(input2-'0') + (int)(input3-'0');

    printf("User's First Input: (Press any key to continue) ");
    scanf("\n %c", &input1);

    for(i=0;i<1;i++){
        diceRoll = (rand()%6) + 1;
        printf("%d\n\n", diceRoll);
    }

    printf("User's Second Input: (Press any key to continue) ");
    scanf("\n %c", &input2);

    for(i=0;i<1;i++){
        diceRoll = (rand()%6) + 1;
        printf("%d\n\n", diceRoll);
    }

    printf("User's Third Input: (Press any key to continue) ");
    scanf("\n %c", &input3);

    for(i=0;i<1;i++){
        diceRoll = (rand()%6) + 1;
        printf("%d\n\n", diceRoll);
    }


    printf("Sum of observations: %d", sumDice);

    return 0;
}

sumDice 函数没有输出正确答案,我认为问题出在这个特定函数的某个地方。

int sumDice = (int)(input1-'0') + (int)(input2-'0') + (int)(input3-'0');背后的逻辑是有道理的,但是必须给input1input2input3赋值后才能使用。

你得到了错误的答案,因为当你一开始初始化 sumDice 时,输入变量没有被初始化,所以它们存储了随机值。

这里是你必须放的地方:

int sumDice = (int)(input1-'0') + (int)(input2-'0') + (int)(input3-'0');
printf("Sum of observations: %d", sumDice);

根据此声明判断:

where the user rolls 3 dice and gets some random outputs (up to integer 6). My next step is to add those 3 values obtained and get its sum

我假设你想要这个:

首先将sumDice初始化为0:

int sumDice=0;

然后,在每个 for 循环中,在 diceRoll=rand()... 行之后添加:

sumDice+=diceRoll;

并删除最后 sumDice= (int)(input-'0')... 行。