为什么我的程序无法识别质子号码?

int main()
{
    int n , i , c;
    printf("hello this prog can recognize pronic number\n\n");
    printf("please enter an integer:\n");
    scanf("%d" , &n);
    for (i=1 ; i<=n ; i++)
    {
        c = n / i ;
    }

    if (c==i+1)
    {
        printf("this number is  a pronic number");
    }
    else
    {
        printf("this number is NOT pronic number");
    }

    return 0;
}

最佳答案

仅在循环结束后才评估c的值。您应该随手检查c,如果发现该号码是质子号码,请跳出循环。

还要注意,您正在执行整数除法,因此您可能会找到c==i+1,但是c*i不会等于n

int pronic = 0;
for (i = 1; i <= n; i++) {
    if (i * (i + 1) == n) {
        printf("%d is a pronic number.\n", n);
        pronic = 1;
        break;
    }
}

if (!pronic) {
    printf("%d is not a pronic number\n", n);
}

08-07 02:06