Hello dear fellows,
i wrote a little program to calculate the factorial of a natural number but i can't get it to return useful values. The error detection (n < 0)is working fine, but the rest isn't and i don't get why. It runs somehow, but not the right way. In addition, i only want one output instead of two. Please don't be scared by the german output, i bet you can understand it nonetheless :)
Please help.
#include <iostream>
#include "stdafx.h"
#include "conio.h"
usingnamespace std;
int fak(int n) {
if (n == 0 || n == 1) {
cout << "Die Fakultaet von " << n << " ist 1 .\n";
}
else {
return n*(fak(n - 1));
n--;
}
}
int main(){
int n;
cout << "Bitte die zu fakultierende Zahl eingeben!\n";
cin >> n;
if (n < 0) {
cout << "Eingabe ist keine natuerliche Zahl!\n";
}
else
cout << "Die Fakultaet von " << n << " ist " << fak(n) << " .\n";
_getch();
return 0;
}
You have been right with the missing return value and the decrementation, now it works perfectly fine. Thanks a lot for the fast answer and the correction in my vocabulary, always appreciated!
The working code if anybody else should search for it.