繁体   English   中英

C程序崩溃,不确定为什么吗?

[英]C Program Crashing, not sure why?

#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;
}

首先抱歉缩进。 它不是那么整洁。 该程序会生成5个“骰子”,并尝试获得Yahtzee。 然后,用户可以选择要重新滚动的内容。 此程序或函数中不允许使用数组。 现在,开始讨论这个问题。 我的代码有问题,因为程序在我第一次尝试输入内容时就崩溃了,这是在while循环之后。 当我尝试调试时,这似乎是scanf的问题,但是我不确定要更改哪些内容以使代码起作用,也不确定我在代码中做错了什么,因为我一直在学习C现在在学校待了近一个月。

谢谢,

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

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

scanf("%c", &confirm1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM