我正在麻省理工学院开放式课程中介绍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.也许有人有想法?谢谢你的时间.
更改:
cout << accumulator << '.\n';
Run Code Online (Sandbox Code Playgroud)
至:
cout << accumulator << ".\n";
Run Code Online (Sandbox Code Playgroud)
编译器将多字符文字'.\n'转换为整数11768.此行为是实现定义的.
| 归档时间: |
|
| 查看次数: |
547 次 |
| 最近记录: |