C++ BEGINNER阶乘程序,输出混乱

use*_*447 2 c++ factorial

我正在麻省理工学院开放式课程中介绍C++,下面的代码在教授的第一个问题集中作为计算阶乘的基本程序,并提供了一些相关的问题.

#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;
}
Run Code Online (Sandbox Code Playgroud)

第一个问题是:"输入以下值时会得到什么:0,1,2,9,10?"

答案部分读作"0:1; 1:1; 2:2; 9:362880; 10:3628800",但这不是我发生的事情.我的程序输出"11768",每个明显正确的答案,我不明白为什么.

我看到答案:"0:111768; 1:111768; 2:211768; 9:36288011768; 10:362880011768"

也许代码中有问题,但我没有看到它.我正在使用Visual Studio 2012.也许有人有想法?谢谢你的时间.

Mic*_*eyn 7

更改:

cout << accumulator << '.\n'; 
Run Code Online (Sandbox Code Playgroud)

至:

cout << accumulator << ".\n";
Run Code Online (Sandbox Code Playgroud)

编译器将多字符文字'.\n'转换为整数11768.此行为是实现定义的.

  • 你也可以做std :: cout << accumulator <<"." << std :: endl; (2认同)
  • @lmedinas:有人建议(并且他们已经说服我)你不应该使用`std :: endl`,因为它涉及到流的刷新.如果你只需要一个换行符,使用`<<'\n'`,如果你还需要刷新使用`<<'\n'<< std :: flush;`来使其在其他维护者的代码中显式化你确实想要`flush` (2认同)