D(编程语言)/d2/函数简介
外观
< D(编程语言)
在本课中,您将更多地了解函数,这些函数在第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;
}