【发布时间】:2015-03-19 10:18:25
【问题描述】:
我是一名计算机工程专业的学生,下学期我将开始 C 课程。因此,为了让自己做好一点准备,我开始自学 C,偶然发现了一个有趣的任务,专为我乍看之下的 C 设计,而不是非常高级的水平。
任务是编写一个程序来计算帕斯卡三角中给定位置的值。计算它的公式写为 element = row! /(位置!*(行 - 位置)!)
我编写了一个简单的控制台程序,它似乎可以正常工作,直到我用 large 数字对其进行测试。
在第 16 行和第 3 行尝试这个程序时,它计算的值为 0,虽然很明显不可能有这样的值(实际上它应该计算值为 560),这个三角形的所有单元格应该是整数并且大于一。
我想我遇到了存储和处理大量数字的问题。阶乘函数似乎可以正常工作,而我使用的公式在我尝试大数之前一直有效
到目前为止,在这里找到了最好的解决方案 - How do you printf an unsigned long long int(the format specifier for unsigned long long int)? 使用类型为 uint64_t 的 inttypes.h 库,但它仍然没有给我所需的结果。
#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,这对您没有帮助。
标签: c largenumber pascals-triangle