I'm new to c++ and want to write a program that computes the factorial of a number and displays it. A factorial of a number (written N!) is defined as N * (N-1) * (N-2) * (N-3) ... *1
In other words, 5! = 5 * 4 * 3 * 2 * 1 = 120 and 3! = 3 * 2 * 1 + 6.
Example of output 15 is 1.30767e+012
Can't get it to display error when user enters a number lower than 2 or higher 60.
// Program to calculate factorial of a number
#include <iostream>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
int main(){
//Declare variables and constants
double factorial=1;
double number;
//Prompt the user for input
cout<<"Enter Number To Find Its Factorial (2-60): = ";
cin>>number;
while(number>=1){
factorial*=number;
number--;
}//end while
if(number < 0)
cout<<"Please Only enter Non-Negative Numbers -> "<<number<<endl;
else if(number > 60)
cout<<"Please Enter Number Between (2-60) -> "<<number<<endl;
else
cout<<"Factorial is: "<<factorial<<endl;
Please note, that this is not a homework site. We won't do your homework for you. The purpose of homework is that you learn by doing. However we are always willing to help solve problems you encountered, correct mistakes you made in your code and answer your questions.
We didn't see your attempts to solve this problem yourself and so we cannot correct mistakes you didn't made and answer questions you didn't ask. To get help you should do something yourself and get real problems with something. If your problem is "I don't understand a thing", then you should go back to basics and study again.
The instructions in the program are run sequentially - so right now, the lines to calculate the factorial precede those that check to make sure the number entered was valid. You need to swap those, so that the lines to check input come before the lines to calculate. If an invalid number is entered, does the assignment want you to allow the user to re-input a number or are you just supposed to display an error message, skip the factorial calculation and just exit the program?
If 2 and 60 are valid values, then you'd want < and >, not <= and >= on the error check.
Right now your output statement runs whether they've input a valid # or not. I might use an if/else structure.
1 2 3 4 5 6
if less than 0
//-> error message about negative numbers
elseif less than 2 or greater than 60
//-> error message about out of range
else // number is within valid range
//->loop through to calculate factorial and output result
You could work the descending output into the loop. Your loop right now just goes down to 2, so if you want to have 1 display as the last number displayed in the multiplied numbers, something would need to be tweaked. I might use a for loop like this for (int i = number; i >= 1; i--) and use the value of i to output the current number being multiplied.