易百教程

读取控制台输入

在学习了解读取控制台输入之前,请阅读考虑以下代码:

#include <stdio.h>

int main(void)
{
      float radius = 0.0f;                  // The radius of the table
      float diameter = 0.0f;                // The diameter of the table
      float circumference = 0.0f;           // The circumference of the table
      float area = 0.0f;                    // The area of the table
      float Pi = 3.14159265f;
      printf("Input the diameter of the table:");
      scanf("%f", &diameter);// Read the diameter from the keyboard

      radius = diameter/2.0f;               // Calculate the radius
      circumference = 2.0f*Pi*radius;       // Calculate the circumference
      area = Pi*radius*radius;              // Calculate the area

      printf("\nThe circumference is %.2f", circumference);
      printf("\nThe area is %.2f\n", area);
      return 0;
}

执行上面示例代码,得到以下结果:

hema@ubuntu:~/book$ gcc -o main main.c
hema@ubuntu:~/book$ ./main
Input the diameter of the table:121.98

The circumference is 383.21
The area is 11686.03

声明并初始化五个变量,其中Pi具有其通常的值。以下语句读取圆桌的直径值。
使用新的标准库函数scanf()函数来执行此操作:

scanf("%f", &diameter);  // Read the diameter from the keyboard

scanf()函数是一个需要包含stdio.h头文件的函数。此函数用来处理键盘输入。
它会将用户输入的内容转换为双引号之间的控制字符串。在这个示例代码中,控制字符串是%f,因为需要读取一个float类型的值。
它将结果存储在第二个参数指定的变量diameter中。
第一个参数是一个类似于在printf()函数一起使用的控制字符串。&在变量名称diameter前面称为运算符的地址。
它允许scanf()函数从键盘读取的值存储在变量diameter中。