前置练习

2021年真题

以下代码输出的结果为?

#include <stdio.h>

int main() {
    int x = 10;
    int y = 3.14;
    char a[8] = '1234';
    
    x=strlen(a);y=sizeof(a);
    printf("%d\n", x);
    printf("%d\n", y);
    
    return 0;
}
练习题 1
2023年高考真题

以下程序段的输出结果是什么?

int a = 5, b = 3;
printf("%d %d %d", a, b, a * b);
A 5 3 8
B 5 3 53
C 5 3 15
D 5 * 3=15
解析:

正确答案:C

printf() 函数按顺序输出参数:a=5, b=3, a*b=15。格式字符串中的空格会原样输出。

练习题 2
2022年高考真题

以下使用scanf输入数据的程序段,正确的是:

A scanf("input: %d", &x);
B scanf("%d", &x);
C scanf("%d", x);
D scanf("x=%d", x);
解析:

正确答案:B

scanf() 的格式字符串中不应包含非格式说明符的文本(A、D选项错误),且变量前必须加&符号(C选项错误)。

数学函数

math.h头文件

C语言数学函数包含在math.h头文件中,使用前需要包含该头文件。

#include <math.h>

常用数学函数:

函数 描述 示例
sqrt(x) 平方根 sqrt(9) = 3.0
pow(x,y) x的y次幂 pow(2,3) = 8.0
fabs(x) 浮点数的绝对值 fabs(-3.5) = 3.5
ceil(x) 向上取整 ceil(3.2) = 4.0
floor(x) 向下取整 floor(3.7) = 3.0
sin(x), cos(x), tan(x) 三角函数 sin(M_PI/2) = 1.0

代码示例1

#include <stdio.h>
#include <math.h>

int main() {
    int a = sqrt(121);;
    int b = sqrt(169);;
    
    printf(" %d\n", a+b);
    return 0;
}
注意事项
  • 返回值类型大部分为double
  • 注意浮点数精度问题

代码示例2

#include <stdio.h>
#include <math.h>

int main() {
    double a = 3.0;
    int y = sqrt(169);
    
    printf(" %lf\n", pow(a,3));
    return 0;
}

代码示例3

#include <stdio.h>
#include <math.h>

int main() {
    int a = -0x23;
    int b = -0;
    
    printf(" %d\n", abs(a)+abs(b));
    return 0;
}

代码示例4

#include <stdio.h>
#include <math.h>

int main() {
    float a = 3.14159;
    float b = -56.133;
    
    printf(" %.f,%.f\n", fabs(a),fabs(b));
    return 0;
}
练习题 1
2023年高考真题

以下程序段的输出结果是什么?

double x = 10.5;
printf("%.0f", floor(x) + ceil(x));
A 20
B 20.5
C 21
D 21.0
解析:

正确答案:C

floor(10.5)=10.0, ceil(10.5)=11.0, 相加结果为21.0,但%.0f格式会输出21。

练习题 2
2021年高考真题

计算直角三角形的斜边长度,需要包含哪个头文件?

A stdio.h
B math.h
C stdlib.h
D string.h
解析:

正确答案:B

计算斜边需要使用sqrt()函数,该函数在math.h头文件中声明。

数学函数总结

  • 常用数学函数包含在math.h头文件中
  • 注意浮点数的精度问题
  • 三角函数使用弧度制而非角度制
  • 数学函数的返回值
易错点
  • 忘记包含math.h头文件
  • 将角度值直接传入三角函数
  • 混淆ceil()和floor()函数的功能

课程总结与易错点

字符串函数总结

  • strlen()用于获取字符串长度
  • strcpy()用于字符串复制
  • strcat()用于字符串连接
  • strcmp()用于字符串比较
易错点
  • 忘记为目标字符串分配足够空间
  • 混淆strcpy和strncpy的安全性问题
  • 未处理字符串结尾的'\0'字符
  • 混淆strcmp的返回值含义

其他常用函数总结

  • rand()和srand()用于生成随机数
  • time()用于获取当前时间
  • exit()用于程序退出
易错点
  • 忘记调用srand()初始化随机种子
  • 未包含stdlib.h头文件
  • exit()与return混淆使用

综合练习题

代码示例1

#include <stdio.h>
#include <math.h>

int main() {
    char a[]="dfds";
    char b[]="gred";
    strcpy(a,b+2);
    printf(" %s\n", a);
    return 0;
}

代码示例2

#include <stdio.h>
#include <math.h>

int main() {
    char *s="awrg\108\0123";
    printf(" %d\n", strlen(a));
    return 0;
}
综合题
2023年高考真题

以下代码的输出结果是什么?

#include <stdio.h>
#include <math.h>

int main() {
    double x = 4.0;
    printf("%.1f", sqrt(x) + pow(2, 3));
    return 0;
}
A 6.0
B 8.0
C 10.0
D 12.0
解析:

正确答案:C

sqrt(4.0)=2.0, pow(2,3)=8.0, 相加结果为10.0。