Skip to content

Commit

Permalink
小修改
Browse files Browse the repository at this point in the history
  • Loading branch information
Minsecrus committed Sep 15, 2024
1 parent 9852955 commit ff24fb6
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
26 changes: 26 additions & 0 deletions 教程/正文/语法和标准库/2_初识C/2_6_初识断言.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# 初识断言 (Assertion)

## 1. 什么是断言

断言是用于进行 **调试****错误处理** 的工具。

它允许程序员在代码中插入条件检查,以确保程序在运行时满足特定的前提条件。

如果断言的条件不成立,程序将中止执行并生成一条错误消息,提供关于出错位置和原因的信息。

## 2. 使用断言

```c
#include <assert.h>

int main(void){
int a = -5;
assert(a > 0);
}
```
程序中止执行,因为断言的条件 `a > 0` 不成立。
## 3. 用途
用于 **防御性编程**,缩小错误可能存在的范围,便于调试。
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

Expand Down
6 changes: 6 additions & 0 deletions 教程/示例代码/语法和标准库/8_BMI测试.c
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include <assert.h>
#include <stdio.h>

int main()
Expand All @@ -7,9 +8,14 @@ int main()
// 获取用户输入
printf("请输入您的体重(单位:千克):");
scanf("%f", &weight);

assert(weight != 0);

printf("请输入您的身高(单位:厘米):");
scanf("%f", &height);

assert(height != 0);

// 换算
height /= 100;

Expand Down

0 comments on commit ff24fb6

Please sign in to comment.