🌺博客汇总:🌃Summary And Schedule🌠

🌸考研相关内容汇总:考研Schedule&&Summary

🌼408王道C督学课程目录:《王道C语言督学班目录》

本章需要掌握:

  • 1、定义数组长度必须固定,定义数值数组两种方式int a[10]; 或 int a[10] = {0,0,0};
  • 2、定义字符数组的三种形式,字符数组以’\o’结尾
  • 3、scanf(“%s”,arr)、strlen(c)、strcat(c,d)加、strcpy(c,d)赋值给c、strcmp(c,d)比较-1/0/1
  • 4、注:四个函数在<string.h>库

1、数组定义

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>

int main() {
//1、定义方式一
int a[10];
int b[10]={1,2,3,4,5,6,7};
//2、定义方式二
char c[10];
char d[10]={'a','b','c'};
printf("%d\n",b[4]); //越界访问会造成数值异常
printf("%c\n",d[2]); //下标可以直接访问
}

2、字符数组

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>

int main() {
char a[10]; //字符数组结束必须是'\0',也就是a[9]='\0'
scanf("%s",a); //scanf用%s写入字符串
char b[10]="hello";
char c[10]={'h','e','l','l','o'}; //c[9] = '\0'

printf("%s",a);
printf("%d\n",b[1]); //越界访问会造成数值异常
printf("%c\n",c[9]); //下标可以直接访问
return 0;
}

3、gets、puts

1
2
3
4
5
6
7
8
9
//char *gets(char *str);
//int puts(char *str)
char c[20];
gets(c);
puts(c)

//可以用下面的代码代替
scanf("%s",&c);
printf("%s",c);

4、str系列

1
2
3
4
5
#include <string.h>
strlen(c); //字符串c+d
strcat(c,d); //字符串c+d
strcpy(d,c); // 字符串d = c
strcmp(c,d); // 比较字符串c和d的大小 1 0 -1

🌺5、OJ作业

网站:http://oj.lgwenda.com/

1、统计数字(Statistics)

描述:输入N个数(N小于等于100),输出数字2的出现次数;

输入:输入的格式是两行。第一行输入要输的元素个数,比如5;第二行输入 1 2 2 3 2,那么输出结果为3,因为2出现了3次。

输出:统计数字2出现的次数

🌺🌺🌺题解ヾ(^▽^)ゞ🌼🌼🌼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>

int main() {
int element_count;
int arr[100];
scanf("%d",&element_count);
int i;
for(i=0;i<element_count;i++)
{
scanf("%d",&arr[i]);
}

int count=0;
for(i=0;i<element_count;i++)
{
if(arr[i]==2)
{
count++;
}
}
printf("%d\n",count);
return 0;
}

2、字符串翻转(String-Reverse)

描述:读取一个字符串,字符串可能含有空格,将字符串逆转,原来的字符串与逆转后字符串相同,输出0,原字符串小于逆转后字符串输出-1,大于逆转后字符串输出1。例如输入 hello,逆转后的字符串为 olleh,因为hello 小于 olleh,所以输出-1(注:strcmp返回的是正负值而不是+1or-1)

输入:输入一个字符串,例如 hello,当然输入的字符串也可能是 how are you,含有空格的字符串

输出:输出是一个整型数,如果输入的字符串是hello,那么输出的整型数为-1

🌺🌺🌺题解ヾ(^▽^)ゞ🌼🌼🌼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <string.h>
//字符串翻转,翻转后比较与原字符串是否相等
//使用增量编写法
int main() {
char c[100];//原字符串
char d[100]={0};//翻转后的,初始化的目的是为了d有结束符
scanf("%s",&c);
int i,j;
for(i=0,j= strlen(c)-1;i< strlen(c);i++,j--)
{
d[j]=c[i];
}
int result=strcmp(c,d);
if(result>0)
{
printf("%d\n",1);
} else if(result<0)
{
printf("%d\n",-1);
} else{
printf("%d\n",0);
}
return 0;
}