C程序崩溃,不知道为什么?

时间:2016-03-03 03:47:25

标签: c

#include <stdio.h> 
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <ctype.h>

int main () {

int dice1; //declaring variables
int dice2;
int dice3;
int dice4;
int dice5;
int rolls = 0;
int diceRolls = 0;
bool reroll1 = false;
bool reroll2 = false;
bool reroll3 = false;
bool reroll4 = false;
bool reroll5 = false;
char confirm1; //no arrays, as mentioned in the rubric :) ...
char confirm2;
char confirm3;
char confirm4;
char confirm5;

srand(time(0)); //seeding

printf("DICE 1\t"); //formatting so the users know which dice is which for later
printf("DICE 2\t");
printf("DICE 3\t");
printf("DICE 4\t");
printf("DICE 5\n");

dice1 = rand() % 6 + 1;
printf("%d\t", dice1);

dice2 = rand() % 6 + 1;
printf("%d\t", dice2);

dice3 = rand() % 6 + 1;
printf("%d\t", dice3);

dice4 = rand() % 6 + 1;
printf("%d\t", dice4);

dice5 = rand() % 6 + 1;
printf("%d\t\n", dice5);

while ((dice1 != dice2) || (dice2 != dice3) || (dice3 != dice4) || (dice4 != dice5)) { //The loop determines that if Yahtzee is not achieved, it will reroll until it is

    rolls ++;

    printf("Reroll die 1?(y/n)\n");
    scanf("%c", confirm1);
    if (tolower(confirm1) == 'y') {
       reroll1 = true;
       dice1 = rand() % 6 + 1;
    }

    printf("Reroll die 2?(y/n)\n");
    scanf("%c", confirm2);
    if (tolower(confirm2) == 'y') {
       reroll2 = true;
       dice2 = rand() % 6 + 1;
    }

    printf("Reroll die 3?(y/n)\n");
    scanf("%c", confirm3);
    if (tolower(confirm3) == 'y') {
       reroll3 = true;
       dice3 = rand() % 6 + 1;
    }

    printf("Reroll die 4?(y/n)\n");
    scanf("%c", confirm4);
    if (tolower(confirm4) == 'y') {
       reroll4 = true;
       dice4 = rand() % 6 + 1;
    }

    printf("Reroll die 5?(y/n)\n");
    scanf("%c", confirm5);
    if (tolower(confirm5) == 'y') {
       reroll5 = true;
       dice5 = rand() % 6 + 1;
    }

    if (reroll1) {
        printf("%d\t", dice1);
    } 

    if (reroll2) {
        printf("%d\t", dice2);
    }

    if (reroll3) {
        printf("%d\t", dice3);
    }

    if (reroll4) {
       printf("%d\t", dice4);
    }

    if (reroll5) {
        printf("%d\t\n", dice5);
    }       
}

system("cls"); //clear screen for a better look

diceRolls = rolls * 5; //calculating dice rolls

printf("STATS\n"); //shows user stats
printf("Amount of rolls to achieve Yahtzee!: %d\n", rolls);
printf("Number of dice rolled: %d", diceRolls);

return 0;
}

首先对于缩进感到抱歉。它不是那么整洁。这个程序生成“roll”5 die,并试图获得Yahtzee。然后,用户可以选择决定重新注册的内容。此程序或函数中不允许使用任何数组。现在,关于这个问题。我的代码有问题,因为程序在第一次尝试输入内容时崩溃,这是在while循环之后。当我尝试调试时,似乎scanf是这里的问题,但是我不知道要改变什么来让代码运行,并且我不确定我在代码中做错了什么,因为我一直在学习C在学校接近一个月了。

谢谢,

1 个答案:

答案 0 :(得分:6)

scanf获取变量的地址以将用户输入写入变量。您只传递变量名称(值)而不是地址。 &是运算符,当它以变量名称为前缀时,给出该变量的地址。

使用scanf的正确方法如下所示,这可以解决您的问题。对程序中的其他scanf语句使用相同的语句。

scanf("%c", &confirm1);