跳轉到內容

D 語言入門指南/條件語句和迴圈/簡單分支

來自華夏公益教科書,自由的教科書


if 條件語句

[編輯 | 編輯原始碼]

示例:更復雜的輸入 - 一個詢問年齡並給出“聰明”回應的程式

import std.c.stdio;
import std.stdio;

void main()
{
  // Create a variable that can hold an integer
  int age;
  
  // writef does not flush on all platforms. If you remove fflush
  // below, the text might be written after you enter your number.
  writef("Hello, how old are you? ");
  fflush(stdout);

  // scanf reads in a number. %d tells scanf it is a number and the number
  //   is placed in the variable 'age'.
  // The & sign in &age tells the compiler that it is a reference to the
  //   variable that should be sent. 
  scanf("%d",&age);

  // Print different messages depending on how old the user is.
  if(age < 16) 
  {
    // If age is below 16 you are not allowed to practice car-driving in Sweden
    writefln("You are not old enough to practice car driving!");
  }
  else if (age < 18) /* 16 <= age < 18 */
  {  
    writefln("You may practice if you have a permission, but not drive alone!");
  } 
  else /* You are at least 18 so everything should be alright */
  {
    writefln("You may drive as long as you have a licence!");
  }
}
華夏公益教科書