Home > OS >  Why wont my factorial program result in the right answers?
Why wont my factorial program result in the right answers?

Time:01-15

I am attempting to write a C program that can calculate the factorial of a number inputted by a user. I have the program below, and it seems to work fine without any errors. However, everything I input a number like 5, I get a strange answer like -1899959296.

I cant seem to find where the error is, let alone how the answer is negative. Any help would be appreciated, thank you very much.

int main()
{
    int inputnumber;
    int n;
    
    printf("\nThis program is a factorial calculator. Input a number below to finds its factorial: ");
    scanf("%i", &inputnumber);
    
    //A 'for' loop repeats the same contained statements until a condition is met.
    //A general form of a 'for' statements is shown below:
    
    // for( initial values; loop condition; loop expression)
    
    for (n = 1; n <= inputnumber; n  )
    {
        inputnumber = inputnumber * n;
    }
    
    printf("\nThe answer is %i", inputnumber);

    return 0;
}

I attempted to make a factorial program, but all inputted numbers give very wrong answers.

CodePudding user response:

The problem is this part of your code:

for (n = 1; n <= inputnumber; n  )
{
    inputnumber = inputnumber * n;
}

The code inside the loop increases inputnumber when n > 1. This causes the loop to run much longer than intended because n <= inputnumber (your loop conditional) is always satisfied until there is an integer overflow, i.e., when inputnumber < 0. Hence, the loop only stops when inputnumber becomes negative.

To fix this, you should store your factorial result as a separate variable, e.g.:

int result = 1;

Then update your loop to be result *= n; (and obviously change your print statement accordingly).

CodePudding user response:

If you changed your conditional portion of your for loop to restrict to only < rather than <= it should produce the right answers.

For example i assume the input: '2' gives you '4' as a result:

input = 2 * 1
input = 2 * 2
end
return input

or by using a third variable you can use your current logic: #include <stdio.h>

int main() {
    int number, i, factorial = 1;
    printf("Enter an integer: ");
    scanf("%d", &number);
    for (i = 1; i <= number; i  ) {
        factorial *= i;
    }
    printf("Factorial of %d = %d\n", number, factorial);
    return 0;
}
  • Related