我刚开始学习D语言,并试图编写一个简单的阶乘程序。D语言中是否有类似C++中的向量 (vectors)?我想使用向量来创建一个动态函数来计算阶乘。
我刚开始学习D语言,并试图编写一个简单的阶乘程序。D语言中是否有类似C++中的向量 (vectors)?我想使用向量来创建一个动态函数来计算阶乘。
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]
ulong
(2 ^ 64
),您也只能计算到20的阶乘,对于这种情况,内联表格可能更合适。以下是使用BigInt
的示例:import std.bigint : BigInt;
BigInt factorial(int n)
{
auto b = BigInt(1);
foreach (i; 1..n + 1)
b *= i;
return b;
}
void main ()
{
import std.stdio : writeln;
factorial(10).writeln; // 3628800
factorial(100).writeln; // 9.33 * 10^157
}