跳轉至內容

D(程式語言)/d2/函式簡介

50% developed
來自Wikibooks,開放世界中的開放書籍

第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;
}
華夏公益教科書