저는 컴퓨터 공학 학생이며 다음 학기에 C 코스를 시작할 예정입니다. 그러니 약간 자신을 준비하기 위해, 저는 혼자서 C를 배우기 시작했고, 처음에는 어떻게 보 였는지, 매우 진보 된 수준으로는 보이지 않는, 재미있는 일을 발견했습니다.파스칼의 삼각형 (C 언어)
주어진 위치의 값을 계산하는 프로그램을 작성하려면 파스칼의 삼각형. 그리고 그것을 계산하기 위해 주어진 수식은 요소 = 행으로 기록됩니다!/(위치! * (행 위치)!)
개의 숫자로 테스트 할 때까지는 괜찮은 것으로 보이는 간단한 콘솔 프로그램을 작성했습니다.
이 프로그램을 행 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 라이브러리를 사용하지만 아직 제공하지 않습니다. 나에게 필요한 결과. 당신이 당신의 중간 계산을 위해 정기적 INT 변수를 사용하는 경우 64 비트 정수가 차이를하지 않습니다 반환하는 경우에도
#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'로 캐스팅되어 실제로 도움이되지 않습니다. –