简体   繁体   English

一个简单的递归函数打印出奇怪的东西

[英]A simple recursion function prints weird stuff

So I need to code a recursive function that validates if the number is a prime number. 所以我需要编写一个递归函数来验证数字是否为素数。 The algorithm is pretty simple and works correctly, it's just that when I print the function rather than showing 1 or 0 it shows random crap (maybe addresses?) and I couldn't find out why. 算法很简单,工作正常,只是当我打印函数而不是显示1或0时,它显示随机废话(可能是地址?),我找不到原因。

The code: 编码:

int isPrimal(int n, int p) {
    if (p == 1) {
        return 1;
    }
    if (n % p == 0) {
        return 0;
    }
    isPrimal(n, p - 1);
    printf("n = %d i = %d\n", n, p);    
}

int main() {
    int numcase, *A, sizeA = 0, i = 0, cnt3dig = 0, n, p;

    printf("Enter a number to check for primality\n");
    scanf("%d", &n);
    p = (n - 1);
    printf("The result is 1 if the number is a prime, 0 otherwise\n");
    isPrimal(n, p);
    printf("The result is %d\n", isPrimal);
}

You are printing the address of the isPrimal() function, you should change it to 您正在打印isPrimal()函数的地址,您应该将其更改为

printf("The result is %d\n", isPrimal(n, p));

and don't forget to check scanf() 's return value. 并且不要忘记检查scanf()的返回值。

The printf in main invokes undefined behavior because you pass the address of the function isPrimal instead of its result: change printf("The result is %d\\n", isPrimal); 所述printfmain调用未定义的行为,因为你传递函数的地址isPrimal而不是其结果是:改变printf("The result is %d\\n", isPrimal); to

printf("The result is %d\n", isPrimal(n, p));

Furthermore, your algorithm is very inefficient. 此外,您的算法效率非常低。 Function isPrimal calls itself recursively n-2 times. 函数isPrimal递归调用n-2次。 If you remove the printf statement, the compiler notices the tail call to itself and turns this recursion into a loop. 如果删除printf语句,编译器会注意到对自身的尾调用,并将此递归转换为循环。 When you have the printf statement it cannot do this and for large values of n you probably recurse too deep and cause a Stackoverflow . 当你有printf语句时,它不能这样做,对于大的n值你可能会过于沉重并导致Stackoverflow

There are 2 changes that are necessary 

1. In main, While printing the output make a function call -not a reference to the location of the function. 1.在main中,打印输出时进行函数调用 - 不是对函数位置的引用。 2. In isPrimal, Call the isprimal recursively after the print statement. 2.在isPrimal中,在print语句之后递归调用isprimal。

#include<stdio.h>
#include<stdlib.h>
  int isPrimal(int n, int p) {
    if (p == 1) {
        return 1;
    }
    if (n % p == 0) {
        return 0;
    }
    printf("n = %d i = %d\n", n, p);
    isPrimal(n, p - 1);
}

int main() {
    int numcase, *A, sizeA = 0, i = 0, cnt3dig = 0, n, p;

    printf("Enter a number to check for primality\n");
    scanf("%d", &n);
    p = (n - 1);
    printf("The result is 1 if the number is a prime, 0 otherwise\n");

    printf("The result is %d\n", isPrimal(n, p));
    return 1;
}

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

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