简体   繁体   English

Pascal的Triangle程序不起作用

[英]Pascal's Triangle program not working

I'm very new to C, although I've done a decent amount of Java before. 我对C还是很陌生,尽管以前我做过很多Java。 I'm making a basic Pascal's Triangle program and I've been looking at it for an hour trying to get it working. 我正在制作一个基本的Pascal的Triangle程序,并且已经花了一个小时的时间试图使其正常工作。 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. double fact(int num) ,应明确初始化变量result Also, I would suggest you to define both the return value of the function and variable result to int type. 另外,我建议您将函数的返回值和变量resultint类型。

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? 也许您需要将其初始化为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; 第一次,我== 0; which means output2 at best will be 0 (assuming its automatically initialized to 0). 这意味着output2最多为0(假设其自动初始化为0)。 If output2 == 0, output5 might be undefined. 如果output2 == 0,则可能未定义output5。 I say might because of double-precision numbers it may actually not be exactly 0. 我说可能是因为双精度数字,实际上可能不完全是0。

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

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