跳转到内容

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!");
  }
}
华夏公益教科书