D(编程语言)/d2/函数入门
外观
< D(编程语言)
(重定向自 D(编程语言)/d2/第 3 课)在本课中,你将看到更多关于函数的知识,这些函数在第 1 课中已经使用过。如果你已经熟悉其他类似 C 的语言,你只需要快速浏览一下即可。
import std.stdio;
int watch_tv(int first_watched, int then_watched, string channel = "The PHBOS Channel")
{
writefln("Finished watching %s.", channel);
return first_watched + then_watched;
}
int commercials(int minutes)
{
writefln("Watching %s minutes of commercials.", minutes);
return minutes;
}
int cartoons(int minutes)
{
writefln("Watching %s minutes of cartoons.", minutes);
return minutes;
}
void main()
{
auto minutesoftv = watch_tv(commercials(10), cartoons(30));
writeln(minutesoftv, " minutes of TV watched!");
}
/*
Output:
Watching 10 minutes of commercials.
Watching 30 minutes of cartoons.
Finished watching The PHBOS Channel.
40 minutes of TV watched!
*/
函数允许你编写更结构化的代码。使用函数,你可以编写一些代码一次,然后在需要使用该代码时随时调用它。
让我们来看看语法
return_type name_of_function(arg1type arg1, arg2type arg2)
{
// function body code here
return something;
}