| ReDoX (2) | ||||||
|
I'm very new to C++ and I'm making a program that calculates the factorial of a number. Just in case someone doesn't know, the factorial of a number is the sum of all numbers starting at 1 and ending at the number itself. Eg. The Factorial of 3 = 1 + 2 + 3 = 6. So here is my code uptill now:
When I compile that, the Welcome function works fine. But when I enter 5 (For example), a valid input, the cursor goes to the next line and keeps blinking:
If I enter -5, it will ask me to enter a positive number. Then if I enter 4, for example, it hangs again:
But lets say I enter 4.5. It will ask me to enter an integer, so I enter 5. Then the program works fine and outputs 5:
What's wrong? | ||||||
|
|
||||||
| iambehnam (6) | |||
|
Hello. You don't have calculate 1+2+...+num . why? don't you use for() instead of three if() in your check function? use this code too:
good luck; | |||
|
|
|||
| ReDoX (2) | |||
I already made a simple program like that once but now I wanted to make it more complex. I want to the user to be able to enter any number he wants and the program should decide whether or not the input is valid. As I said before, the above code is not complete. The calculations aren't done yet. And maybe unknowingly, you answered my question! I had an extra 'if' for some reason.
HAHA. God knows why I did that. I resumed this program after a long time, maybe that's why. But Thank you! | |||
|
|
|||
| Chervil (1206) | ||
Actually that's the sum of the integers. The factorial is the product of the integers. The Factorial of 3 = 1 * 2 * 3 = 6. It happens in this case to give the same result, 6. But 4! = 1*2*3*4 = 24 | ||
|
|
||
| nathan10 (122) | ||
Furthermore, no huge program is needed to compute the sum of positive integers between any two values. Carl Gauss developed a neat formula for that. sum = n * (n+1) / 2; when the lower integer is 1. sum = (upper integer - lower integer + 1) * (lower integer + upper integer) / 2; when the lower integer is greater than 1.
| ||
|
|
||