C语言(一)

初识C语言

特点

易懂,可靠,高效,可移植,强大而灵活,面向过程

逻辑值

C语言中用值1表示true,值0表示false。

使用C语言的7个步骤

1.定义程序的目标 2.设计程序 3.编写代码 4.编译 5.运行程序 6.测试和调试程序 7.维护和修改程序

C语言标准

C11标准

开发环境

VS2019或者VScode+WSL

书籍

C Primer Plus

Hello World

1
2
3
4
5
6
7
#include <stdio.h> //include:包含 stdio.h:standard input out.head标准输入输出的头文件
int main(void)
{
printf("Hello World!\n"); //print 打印 format 格式化 printf 格式化输出

return 0;
}

数据类型

int类型

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main(void)
{
int x = 100;

printf("dec = %d; octal = %o; hex = %x\n", x, x, x);
printf("dec = %d; octal = %#o; hex = %#x\n", x, x, x);

return 0;
}

char类型

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int main(void)
{
char ch;

printf("Please enter a character.\n");
scanf("%c", &ch);
printf("The code for %c is %d.\n", ch, ch);

return 0;
}

_Bool类型

_Bool类型,用于表示布尔值,即逻辑值true和false。

可移植类型

stdint.h和inttypes.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <inttypes.h>
int main(void)
{
int32_t me32;

me32 = 45933945;
printf("Frist, assume int32_t is int: ");
printf("me32 = %d\n", me32);
printf("Next, let's not make any assumptions.\n");
printf("Instead, use a \"macro\" from inttypes.h: ");
printf("me32 = %" PRId32 "\n", me32);

return 0;
}

浮点类型

float,double和long double

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
int main(void)
{
float aboat = 32000.0;
double abet = 2.14e9;
long double dip = 5.32e-5;

printf("%f can be written %e\n", aboat, aboat);
printf("And it's %a in hexadecimal, powers of 2 notation\n", aboat);
printf("%f can be written %e\n", abet, abet);
printf("%Lf can be written %Le\n", dip, dip);

return 0;
}

复数和虚数类型

虚数类型是可选的类型。
复数的实部和虚部类型都基于实浮点类型来构成
复数类型:float _Complex double _Complex long double _Complex
虚数类型:float _Imaginary double _Imaginary long double _Imaginary

类型大小

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
int main(void)
{
printf("Type int has a size of %zd bytes.\n", sizeof(int));
printf("Type char has a size of %zd bytes.\n", sizeof(char));
printf("Type long has a size of %zd bytes.\n", sizeof(long));
printf("Type long long has a size of %zd bytes.\n", sizeof(long long));
printf("Type double has a size of %zd bytes.\n", sizeof(double));
printf("Type long double has a size of %zd bytes.\n", sizeof(long double));

return 0;
}

如何声明简单的变量

1,选择需要的类型。
2,使用有效的字符给变量起一个变量名。
3,按以下格式进行声明:类型说明符 变量名;
类型说明符由一个或多个关键字组成。

1
2
int erest;
unsigned short cash;

4,可以同时声明相同类型的多个变量,用逗号分隔各变量名。
char ch, init, ans;
5,在声明的同时还可以初始化变量。
float mass = 6.0E24;

字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#define PRAISE "You are an extraordinary being."

int main(void)
{
char name[40];

printf("What's your name? ");
scanf("%s", name);
printf("Hello, %s. %s\n", name, PRAISE);

return 0;
}