#include <stdio.h>
long factorial(int num)
{
int counter;
int fact = 1;
for (counter = num; counter > 0; counter--) fact *= counter;
return fact;
}
float combinations(int n, int k)
{
int 开发者_如何学运维numerator = factorial(n);
int denominator = factorial(k) * factorial(n-k);
float fraction = numerator/denominator;
return fraction;
}
int main()
{
printf("How many rows of Pascal\'s triangle should I print?\t");
int rows = GetInteger();
int counter;
int counter2;
for (counter = 1; counter <= rows; counter++)
{
int y = rows-counter;
for (; y > 0; y--) printf(" ");
for (counter2 = 0; counter2 <= counter; counter2++)
printf("%6.0lu", (long) combinations(counter, counter2));
printf("\n");
}
}
Every time I go past twelve rows, the numbers start to decrease. What am i doing wrong?
And, GetInteger()
is just a scanf()
with a few touch ups. I am 100% sure it works perfectly.
After 12th row factorial and so pascal triangle elements become too large so int type cannot hold them - so you get overflow (most probably values you get are wrapped around maximum int value).
P.S. why do you use 3 different types in your code (long, int, float)? As k!*(n-k)! always divides n! you do not need float value (you use integer division and cast result to long anyway). Just use the biggest integer type you can, or some custom BigInt type that can hold integer numbers of arbitrary length - so you can show correct values for large row numbers.
Don't start from factorials. Start from the following facts about Pascal's triangle:
- the nth row of the triangle has n elements (if we start counting from 1)
- the first and last elements of each row are 1
- each element aside from the first and last one is the sum of the two elements diagonally above it (if the triangle is written in a symmetric way)
You will of course be limited by the size of the data type you are holding results in, but not any sooner than necessary (by intermediate results such as factorials).
INT_MAX is usually 2,147,483,647
12! is 479,001,600
13! is 6,227,020,800 but your function factorial(13)
returns 1,932,053,504 (= 6,227,020,800 - 4,294,967,296)
精彩评论