Hello, I recently purchased a book in C++ and one of the exercises is to create a simple factorial function. All it is supposed to do is take all the whole numbers leading up to another number and multiply them together. For example 5:
1 * 2 * 3 * 4 * 5 = 120
I can't figure out for the life of me what I am doing wrong. I know I am a total rookie but some help would be appreciated thanks.
My code looks like this:
#include <iostream>
#include <math.h>
usingnamespace std;
int calc(){
int n;
int x;
int total;
cout << "Enter a number to be factorialized to\n";
cin >> n;
for(x = 1; x <= n; x++){
total = x * x++;
cout << total << endl;
}
}
int main()
{
calc();
}
The issue is misunderstanding the ++ operator (and another few things, but this first) - when you write var++ is makes a copy of the var, increments the original, and then gives back the copy to the expression (aka the old value), so your code is squaring a number. When you do ++var it simple increments it and returns it so you get the new value.
The other issue is, total serves no purpose because eventually you just assign n * (n+1) to it without considering its previous values. Perhaps you meant total *= x++ ?
Thanks but I'm still lost. I tried correcting what u said and then some but I still can't get it to work :|
Do you have any suggestions on how I could actually get the correct calculation down? I'm pretty sure that just x * (x+1) isn't the correct way now that I look closer. Every time 1 is added to x I need to multiply that new version of x to x++. Like if it is 5 I need it to be multiplied by 6. Thanks for your help though.
Yes and I get 4 very long numbers. Unless I am using it in the wrong spot, which I probably am.... Like I said, I'm a rookie! This is what the code looks like:
#include <iostream>
usingnamespace std;
int calc(){
int n;
int x;
int total;
cout << "Enter a number to be factorialized to\n";
cin >> n;
for(x = 1; x <= n; x++){
total *= x++;
cout << total << endl;
}
}
int main()
{
calc();
}
Thanks but I still get the same result :( The exercise is in the functions section of the book so maybe I should have to call another function or something?