C语言程序设计基础


变量、数据类型与I/O

计算机学院    杨已彪

yangyibiao@nju.edu.cn

提纲

  • 变量

  • 数据类型

  • I/O


Review

Program = Input + Data + Operations + Output


Overview

Variables (变量)   Data Types (数据类型)


Operators (运算符)   Expressions (表达式)

Assignment Statements (赋值语句)


I/O (Input/Output; 输入输出)


Circle

Given a radius (say 1010) of a circle,
to compute its circumference and area.


L=2πrL = 2\pi rS=πr2S = \pi r^2


  • 每个结果各占一行
  • 小数点后保留两位

Declaration/Definition (声明/定义)

int radius = 10;


  • Declare/Define a variable called radius.
  • The type of radius is int (integer).
  • radius is initialized to 1010.
  • You can assign other integers to radius.
  • radius refers to a location (&radius) in memory.

Identifiers (标识符)

int radius = 10;


radius is an identifier.

Warning: Do not start with _, which are reserved by C.


Always use meaningful identifiers in a uniform style!!!


Operators, Expressions, Assignment Statements


circumference = 2 * PI * radius

Sphere

Given a radius (say 100100) of a sphere,
to compute its surface area and volume.

A=4πr2V=43πr3A = 4 \pi r^2\quad V = \frac{4}{3} \pi r^3

  • 每个结果占 11
  • 小数点后保留 44
  • 每个结果至少占 1515 字符, 左对齐
    • _______________ : surface_area
    • _______________ : volume

mol

66 克氧气的分子数是多少?


Q=6/32×6.02×1023Q = 6 / 32 \times 6.02 \times 10^{23}


两种格式输出, 结果均使用科学计数法表示

  • 第一行结果, 小数点后保留 33
  • 第二行结果, 保留 55 位有效数字

学校信息管理系统

  • 校名 (EN) / 校址

  • 类型(综合型C/艺术类A/工科类T)

  • 校庆日 (mm-dd-yyyy)

  • 教学质量/研究质量/影响力

  • 平均分/标准差/排名


格式要求


  • 每组信息占一行
  • 各项信息使用 \t 间隔
  • 各项信息遵循特定格式要求

char and <ctype.h>

char and <ctype.h>

A char is actually an int.


C string

C string

char first_name[] = “Tayu”;

A C string is a null-terminated (\0) sequence of characters.

String literal: ‘T’, ‘a’, ‘y’, ‘u’, ‘\0’


  • char first_name[5] = “Tayu”;
  • char first_name[10] = “Tayu”;
  • char first_name[2] = “Tayu”;


Conversion Specification

%[flags][width][.[precision]]specifier

  • %d: decimal int
  • %f: double
  • %e %E: double (d.ddd  e±dd-d.ddd \;\text{e} \pm dd)
  • %c: char
  • %s: C string
  • %%: %


It is up to you to ensure that the type of the actual argument matches the type expected by conversion specifiers.

Undefined Behavior (UB)


%[flags][width][.[precision]]specifier




  • -: left-justified (otherwise, right-justified)
  • ++: always begin with a plus or minus sign

%[flags][width][.[precision]]specifier



  • minimum field width
  • padded with spaces if it has fewer characters

%[flags][width][.[precision]]specifier



  • %d: minimum number of digits
    • expanded with leading zeros when needed
  • %f, %e, %E: number of digits after .
    • default is 6
  • %s: maximum number of characters





https://en.cppreference.com/w/c/io/fprintf


Section 7.21: <stdio.h>, P225–230


Chapter 12: <stdio.h>, P257–262



%[\ast][width]specifier


  • %d: skip white-spaces; match a decimal int
  • %lf: skip white-spaces; match a double
  • %c: match a char (do NOT skip white-spaces)
  • %s: match a sequence of non-white-spaces
  • %%: mathch a %

%[\ast][width]specifier



  • \ast: assignment-suppressing

%[\ast][width]specifier



  • maximum field width to scan





https://en.cppreference.com/w/c/io/fscanf


Section 7.21: <stdio.h>, P231–P237


Chapter 12: <stdio.h>, P263–P268


stdin, stdout, stderr

Input/Output Redirection


printf-error.c   scanf-error.c



A beginners’ guide away from scanf


Do NOT use scanf.


Why does everyone say not to use scanf? What should I use instead?


scanf-c17-ex2.c   scanf-c17-ex3.c


变量与赋值

大多数程序在产生输出之前往往需要执行一系列计算, 因此需要在程序执行过程中有一种 临时存储数据 的方法

变量: (Variable)程序执行过程中临时存储数据的单元

类型: (type)每一个变量都有一个类型, 类型用来说明变量所存储的数据的种类, int, float, double, char, char []


变量与赋值 - 类型

C 有多种类型, 包括int、float、double、char等类型的变量

int变量:

  • (整数integer的缩写)存储整数, 如0, 1, 392-2553
  • 整形的取值范围是受限的, 最大的整数通常是21474836472 147 483 647(23112^{31}-1), 16位机最大整数是3276732 767
  • INT_MAX, INT_MIN (limits.h头文件中定义的常量)
#include <stdio.h>
#include <limits.h>

int main(void) {
  printf("Max: %d, Min: %d", INT_MAX, INT_MIN);
  return 0;
}

变量与赋值 - 类型

float/double 变量: 存储浮点数/双精度浮点数, 即可以带小数位, 如379.125

  • float/double 型变量算术运算通常比int型变量慢

  • float/double 在计算机中是近似存储的

需要注意:

  • float/double 型变量所存储的数值往往只是实际数值的一个近似值
  • float/double 型变量中存储0.1, 可能发现变量值为0.099999999999999870.099 999 999 999 999 87

变量与赋值 - 类型

char 变量: 存储字符, 如’A’

  • 单引号

  • 0000000 ~ 1111111, 0 ~ 127的整数

  • 字符’a’的值是97, 'A’的值是65, '0’的值是48, ’ '的值是32

  • %c

#include <stdio.h>
#include <ctype.h>

int main(void) {
  char gender = 'M';
  printf("%c\n", toupper(gender));
  printf("%c\n", gender + 32);
  return 0;
}

变量与赋值 - 声明

声明: 变量使用前必须对其进行 声明(为编译器所做的描述)

  • 指定变量的类型

  • 说明变量的名字

int main(void)
{
  声明
  语句
}

在C99中, 声明可以不必出现在语句之前


变量与赋值 - 声明

  • 可以一次声明一个变量:
int height;
float profit;
char gender;
char name[20];
  • 可以同时声明多个变量:
int height, length, width, volume;
float profit, loss;
char gender;
char name[30], nation[20], address[60];

变量与赋值 - 赋值

赋值: 通过赋值的方式获得值

height = 8;
lenght = 12;
width = 10;
gender = 'M';

8, 12, 10为常量

char name[30] = "Alex";
char nation[20] = "China";
char address[60] = "XianLin Avenue, Qixia District, Nanjing, China 210023";

变量与赋值 - 赋值

变量在赋值或者以其他方式使用之前必须先声明

height = 9; /*** WRONG ***/
int height;

把包含小数点常量赋值给float型变量时, 最好在常量后加字母f:

float profit = 2150.48f;

double类型的变量赋值不要加字母f:

double pi = 3.14159;

变量与赋值 - 赋值

混合类型赋值:

  • 可以把int型的值赋给double型变量

  • 也可以把double型值赋给int型变量, 但不一定安全

变量与赋值 - 赋值

  • 一旦一个变量被赋值, 它就可以用来帮助计算另一个变量的值:
height = 8;
length = 12;
width = 10;
volume = height * length * width;
/* volume is now 960 */
  • 赋值的右侧可以是涉及常量、变量和运算符的公式(或C术语中表达式)
变量与赋值 - 打印变量的值

printf 可用于打印变量的当前值

int height = 2;
char ch = 'a';
float profit = 1500f;
double pi = 3.14159;

printf("Height: %d\n", height);
printf("Character: %c\n", ch);
printf("Profit: %f\n", profit);
printf("Pi: %lf\n", pi);

%d: int型变量占位符, 用来指明变量height的值显示的位置
%c: char型变量占位符, 用来指明变量ch的值显示的位置
%f: float型变量占位符, 用来指明变量profit的值显示的位置
%lf: double型变量占位符, 用来指明变量pi的值显示的位置

变量与赋值 - 打印变量的值

浮点数

  • 要显示float型变量, 需使用 %f 代替 %d, %f 默认会显示出小数点后6位

  • 如果要强制 %f 显示小数点后 p 位数字, 可以把 .p 放置在 %f 之间, 如:

printf("profit: %.2f", profit);
  • printf 打印的变量数量没有限制
printf("Height: %d Length: %d", height, lenght);

变量与赋值 - 初始化

当程序开始执行时, 某些变量会自动设零, 而大多数则不会

  • 没有默认值并且尚未在程序中赋值的变量是 未初始化的(uninitialized)

  • 若试图访问未初始化的变量, 可能会得到不可预知的结果

变量与赋值 - 初始化

int height = 8;

这里, 数值8是一个初始化式.

同一个声明中可以对任意数量的变量进行初始化, 如:

int height = 8, length = 12, width = 10;

int height, length, width = 10;

变量与赋值 - 打印表达式

printf 的功能不局限于显示变量中存储的数, 它还可以显示任意数值表达式的值, 如:

int volume = height * length * width;
printf("%d", volume);

可改写成:

printf("%d", height * length * width);

:fa-lightbulb-o: C 语言的一个通用原则: 在任何需要数值的地方, 都可使用具有相同类型的表达式

读取输入

scanf 函数: C语言中对应于 printf 的库函数

scanfprintf 中的字母 f 含义相同, 都表示格式化

int i;
scanf("%d", &i); 
/* reads an integer; stores into i */

& 符号通常(但不总是)在使用 scanf 时是必需的

读取输入

读取浮点值的scanf调用:

scanf("%f", &x); 
  • %f 告诉 scanf 查找浮点格式的输入值(数字可能包含小数点, 但不是必须的)