简体   繁体   English

C程序不断崩溃

[英]C program keeps crashing

My program keeps crashing. 我的程序不断崩溃。 The codes seems legit and correct. 该代码似乎合法且正确。 Wonder what's the problem. 想知道是什么问题。

#include <stdio.h>

void queue(int length,int turns){
    int permutations,totalTurns;
    turns++;
    if (length>0){
        queue(length-1,turns);
        if (length>1){
            queue(length-2,turns);
        }
    } 
    else{
        permutations++;
        totalTurns+=turns;
    }
}

int main() 
{
    while(true){
        int length;
        float average;
        int permutations=0;
        int totalTurns=0;

        printf("Queue length: ");
        scanf("%d", &length);
        queue(length,-1);
        average=totalTurns/permutations;
        printf("The average turns are %f", average);
    }
}
    int permutations=0;

    average=totalTurns/permutations;

You're dividing by zero. 您被零除。

Note that the permutations variable you've declared in main() is different from the one in queue() . 请注意,您在main()声明的permutations变量与queue()变量不同。

You should probably return the permutations value from queue() , like this: 您可能应该从queue()返回permutations值,如下所示:

int queue(int length,int turns){
    int permutations = 0;
    ...
    return permutations;
}

int main(void) {
    ...
    int permutations = queue(length,-1);
}

You should declare permutations as a global variable, ie outside main function as well as totalTurns because as others mentioned it's always 0 because even thought you declare it in function queue it's being forgotten outside it. 您应该将置换声明为全局变量,即在main函数以及totalTurns外部,因为正如其他人提到的那样,它始终为0,因为甚至认为您在函数队列中声明它都被其遗忘了。

#include <stdio.h>

static int permutations=0;
static int totalTurns=0;


void queue(int length,int turns){
    turns++;
    if (length>0){
        queue(length-1,turns);
        if (length>1){
            queue(length-2,turns);
        }
    } 
    else{
        permutations++;
        totalTurns+=turns;
    }
}

int main() 
{
    while(true){
        int length;
        float average;
        int totalTurns=0;

        printf("Queue length: ");
        scanf("%d", &length);
        queue(length,-1);
        average=totalTurns/permutations;
        printf("The average turns are %f", average);
    }
}

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

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