Search code examples
c++factorial

C++ BEGINNER factorial program, confusing output


I'm doing intro to C++ on MIT OCW and the following code is given in the professors first problem set as a basic program to calculate factorials, with a few related questions.

#include <iostream>
using std::cout;
using std::cin;
int main () 
{
    short number;
    cout << "Enter a number: ";
    cin >> number;
    cout << "The factorial of " << number << " is ";
    int accumulator = 1;
    for(; number > 0; accumulator = (accumulator * (number--)));
    cout << accumulator << '.\n';
    system("pause>nul");
    return 0;
}

The first question is: "What do you get when you enter the following values: 0, 1, 2, 9, 10?"

The answers section reads, "0: 1; 1: 1; 2: 2; 9: 362880; 10: 3628800," but that is not what happens for me. My program outputs "11768" proceeding each apparently correct answer, and I have no idea why.

The answer set I see: "0: 111768; 1: 111768; 2: 211768; 9: 36288011768; 10: 362880011768"

Perhaps there's something wrong in the code, but I don't see it. I am using Visual Studio 2012. Maybe someone has an idea? Thanks for your time.


Solution

  • Change:

    cout << accumulator << '.\n'; 
    

    To:

    cout << accumulator << ".\n";
    

    The compiler is converting the multi-character literal '.\n' into the integer 11768. This behavior is implementation defined.