gpt4 book ai didi

C++ BEGINNER 阶乘程序,令人困惑的输出

转载 作者:太空狗 更新时间:2023-10-29 23:45:33 25 4
gpt4 key购买 nike

我正在麻省理工学院 OCW 介绍 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;
}

第一个问题是:“当您输入以下值时会得到什么: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'; 

收件人:

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

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

关于C++ BEGINNER 阶乘程序,令人困惑的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com