简体   繁体   中英

Pascal's Triangle program not working

I'm very new to C, although I've done a decent amount of Java before. I'm making a basic Pascal's Triangle program and I've been looking at it for an hour trying to get it working. All the logic seems correct to me but I'll probably die before I realize what's wrong. Here's the program:

#include <stdio.h>
#include <stdlib.h>
double fact(int num);

int main()
{
    int row_index = 0;
    printf("Enter the row index : ");
    scanf("%d",&row_index);
    printf("\n");
    int i;
    double output1 = 0;
    double output2 = 0;
    double output3 = 0;
    double output4 = 0;
    double output5 = 0;
    int output6 = 0;
    for(i = 0; i <= (row_index + 1); i++)
    {
        output1 = fact(row_index);
        output2 = fact(i);
        output3 = row_index - i;
        output4 = fact(output3);
        output5 = output1 / (output2 * output4);
        output6 = (int)(output5);
        printf("%i ",output6);
    }
    return 0;
}

double fact(int num)
{
    double result;
    int i;
    for(i = 1; i <= num; ++i)
        {
            result = result * i;
        }
    return result;
}

The compiler is giving me no errors, and each every time I input a number it gives this as output:

Enter the row index : 6

-2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648

In double fact(int num) , the variable result should be explicitly initialized. Also, I would suggest you to define both the return value of the function and variable result to int type.

See (Why) is using an uninitialized variable undefined behavior? .

At a glance, there seems to be several issues.

First:

double fact(int num)
{
    double result;
    int i;
    for(i = 1; i <= num; ++i)
    {
    result = result * i;
    }
    return result;
}

result is not initialized to anything. Maybe you need to initialize it to 1?

for(i = 0; i <= (row_index + 1); i++)
{
    output2 = fact(i);
    output3 = row_index - i;
    output4 = fact(output3);
    output5 = output1 / (output2 * output4);
}

the first time around, i == 0; which means output2 at best will be 0 (assuming its automatically initialized to 0). If output2 == 0, output5 might be undefined. I say might because of double-precision numbers it may actually not be exactly 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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