我刚开始使用D并试图在D中编写一个简单的阶乘程序。是否在D中有类似C ++的向量?我想使用向量来创建一个动态函数来计算阶乘。

最佳答案

在D中,动态数组是可调整大小的,可以连接起来,就像C ++中的向量一样。
这是带有这样的数组的示例,该数组从stdin读取并写入stdout

import std.stdio;  // for readf and writeln

void main ()  // void for main means "int with return 0 at exit" to OS
{
    int n;
    readf (" %s", &n);  // skip whitespace, then read int in default format
    auto f = [1];  // a dynamic array of int containing a 1
    foreach (i; 1..n + 1)  // for i = 1, 2, 3, ..., n - 1, n
    {
        f ~= f[$ - 1] * i;  // append to f its last element multiplied by i
    }
    writeln (f);  // print the dynamic array in default format
}


输入

10


输出为:

[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]


如注释中所述,有关内置动态数组的更多信息,请参考the documentation



但是,您所提到的动态功能尚不清楚。
而且,通常,我们不需要数组或向量来计算阶乘。
检查RosettaCode以获得在D中计算阶乘的其他几种方法。

关于d - D语言阶乘,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38636236/

10-12 16:31