我是計算機工程專業的學生,下一學期我將開始C課程。所以爲了讓自己準備一下,我開始自己學習C,偶然發現了一個有趣的任務,這個任務是爲了我的乍一看,不是一個非常先進的水平而設計的。C中的Pascal三角形
任務是編寫一個程序來計算給定位置的值,在帕斯卡的三角形。並且給出計算它的公式寫爲element = row! /(位置*(行 - !位置)!)
我已經寫了,似乎工作正常,直到我與大號測試它一個簡單的控制檯程序。
當使用第16行和第3位的程序嘗試此程序時,它將計算值爲0,雖然很明顯不存在這樣的值(實際上它應該計算值爲560),但是此所有單元三角形應該是整數並且大於1。
我想我遇到一個問題存儲和處理大數。階乘函數似乎工作正常,我使用的公式工作,直到我嘗試大量
到目前爲止最好的解決方案是在這裏找到 - How do you printf an unsigned long long int(the format specifier for unsigned long long int)?使用inttypes.h庫類型uint64_t但它仍然沒有給我需要的結果。
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
void clear_input(void);
uint64_t factorial(int x);
int main()
{
// Printing
printf("This program computes the value of a given position in Pascal's Triangle.\n");
printf("You will be asked for row and position of the value.\n");
printf("Note that the rows and positions starts from 0.\n");
printf("\n");
printf(" 1 * 0 \n");
printf(" 1 1 * 1 \n");
printf(" 1 2 1 * 2 \n");
printf(" 1 3 3 1 * 3 \n");
printf(" 1 4 6 4 1 * 4 \n");
printf(" **************** \n");
printf(" 0 1 2 3 4 \n");
printf("\n");
// Initializing
int row, pos;
// Input Row
printf("Enter the row: ");
scanf("%d", &row);
clear_input();
// Input Position
printf("Enter the position in the row: ");
scanf("%d", &pos);
clear_input();
// Initializing
uint64_t element, element_1, element_2, element_3, element_4;
// Previously written as -> element = (factorial(row))/(factorial(pos) * factorial(row - pos));
// Doesn't fix the problem
element_1 = factorial(row);
element_2 = factorial(pos);
element_3 = factorial(row - pos);
element_4 = element_2 * element_3;
element = element_1/element_4;
// Print result
printf("\n");
printf("%"PRIu64"\n", element_1); // Temporary output
printf("%"PRIu64"\n", element_2); // Temporary output
printf("%"PRIu64"\n", element_3); // Temporary output
printf("%"PRIu64"\n", element_4); // Temporary output
printf("\n");
printf("The element is %"PRIu64"", element);
printf("\n");
return 0;
}
void clear_input(void) // Temporary function to clean input from the keyboard
{
while(getchar() != '\n');
}
uint64_t factorial(int x) // Function to calculate factorial
{
int f = 1, i = x;
if (x == 0) {
return 1;
}
while (i != 1) {
f = f * i;
i = i - 1;
}
return f;
}
如果使用大量的(> 32位),然後使用'int'是會得到你不正確的結果。如果您正在使用'uint64_t'數據類型來指定返回類型,那麼您需要使用相同的數據類型來計算您的計算。你的函數現在在內部使用了一個'int',並且結果被隱式地轉換成'uint64_t',這對你沒有什麼幫助。 – 2015-01-21 01:20:23