First, I wrote a program to calculate factorial of a natural number, I know the range of 64-bit integer can handle upto 20!, but the problem is when I run my program under Pelles C it gets wrong answer (very very wrong) for 20!, but others are well result (just 20! doesn't).
------------------------------------------------------------------------------------------------------------------------------
I thaught I had a mistake in my code, but not, my code work very perfect on Visual Studio 2013, the program give exactly result for 20!.
------------------------------------------------------------------------------------------------------------------------------
Second, when I use
scanf_s function, I get an error although I've already included
stdio.h:
------------------------------------------------------------------------------------------------------------------------------
If two of these really are a bugs/errors/misstakes/... I hope two of these will be fixed.
If not, can someone tells me how to find reference to these points or suggest me how to fix this, thanks very much!
------------------------------------------------------------------------------------------------------------------------------
Here is my code:
#include<stdio.h>
#include<windows.h> //Windows enviroment
long long int table[20]; //Reuse previous values to improve performance
long long int fac(int);
void cls(HANDLE hConsole); //Clear screen function
int main(void) {
int n;
HANDLE hStdout;
hStdout=GetStdHandle(STD_OUTPUT_HANDLE);
for (;;) {
cls(hStdout);
fputs("n = ",stdout);
scanf_s("%d",&n); //C11
if (n<0||n>20) { //64-bit integer will only work with factorial of [0..20]
puts("The program has stopped working.");
while ((n=getchar())!=10);
getchar();
break;
}
if (table[n]==0)
table[n]=fac(n);
printf("%d! = %lld\n",n,table[n]);
while ((n=getchar())!=10);
getchar();
}
return 0;
}
long long int fac(int x) {
if (x<2)
return 1;
int i;
long long int t;
t=x;
for (i=2;i<x;i++)
t*=i;
return t;
}
void cls(HANDLE hConsole) {
COORD coordScreen={0,0};
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD dwConSize;
if (!GetConsoleScreenBufferInfo(hConsole,&csbi)) {
return;
}
dwConSize=csbi.dwSize.X*csbi.dwSize.Y;
if (!FillConsoleOutputCharacter(hConsole,(TCHAR)' ',dwConSize,coordScreen,&cCharsWritten)) {
return;
}
if(!GetConsoleScreenBufferInfo(hConsole,&csbi)) {
return;
}
if (!FillConsoleOutputAttribute(hConsole,csbi.wAttributes,dwConSize,coordScreen,&cCharsWritten)) {
return;
}
SetConsoleCursorPosition(hConsole,coordScreen);
}
------------------------------------------------------------------------------------------------------------------------------
Ps: I really love Pelles C IDE and always do C projects on it. I find that the code generate by Pelles C fast at least twice if compare with VS, or 1.5 time faster if compare with Code::Blocks (of course on C mode).