#include <iostream>
using namespace std;
int power(int a, int b); // Subfunction to calculate a^b
int fact(int c); // Subfunction to calculate factorial
int main() {
int x=0;
for(int i=1 ; i<=20 ; i )
x = fact(i) / power (i,i); // needs to calculate like [(1! / 1^1) (2! / 2^2) (3! / 3^3) ...... (20! / 20^20) // assigned x and sum it with counter to calculate final result
cout<<x;
return 0;
}
int power(int a, int b) { // a^b subfunction
unsigned long long int multip=1; // written the biggest type just in case (idk if i need it)
for (int i=1; i<=b; i ) {
multip*=a;
}
return multip;
}
int fact(int c) { // factorial subfunction
unsigned long long int multip=1;
for (int i=c ; i>=1 ; i--) {
multip*=i;
}
return multip;
}
I tried to calculate [(1! / 1^1) (2! / 2^2) ... (20! / 20^20)] but somewhy program didn't work at all. output
I'm sorry if the mistake is obvious I've been trying for long hours and can't think much right now. I will return to the replies with fresh head.Have a good day.
CodePudding user response:
You have some serious problems with your types:
int power(...);
int fact(...);
=> this should be long long
.
In top of this, you are doing integer division, while you need floating point division:
fact(i) / power (i,i);
... should be:
((double) fact(i)) / power (i,i);
CodePudding user response:
Thank you for your comment. It worked. I changed the subfunctions " int --> unsigned long long " but I didn't understand the reason of making division in "double". What is wrong with doing with decimals? Secondly:
((double) fact(i)) / power (i,i);
why did you only take fact(i) into brackets? Doesn't it need to be like. Has given the same result though:
x = (double) fact(i) / power (i,i);
That's all. Thank you for your help, I appreciate it.