11.2const的用法
const的全称是constant,意思为不变的,恒定的。在这里就是常量。
变量:可以被改变的量
常量:不能被改变
在定义变量的时候加上const这个量就不变了:
const int a=100;
const int Any=200;
注:常量一旦创建其值就不能改变,因此常量必须再定义的时候初始化,后面的任何赋值行为都会引发错误,技术初始化常量可以使用任意形式的表达式,但是不能再次赋值。
常量只允许接收一次值。
灵活的定义和初始化常量值:
#include<stdio.h>
int gv() {
return 80;
}
int main() {
int n = 100;
int m1 = n;
int m2 = 90;
int m3 = gv();
printf("%d\n%d\n%d\n",m1,m2,m3);
return 0;
}
#include<stdio.h>
int gv() {
return 80;
}
int main() {
int n = 100;
const int m1 = n;
const int m2 = 90;
const int m3 = gv();
printf("%d\n%d\n%d\n",m1,m2,m3);
return 0;
}
注:常量不可以修改
const和指针:
指针本身不可变:
int * const p1
指针指向的数据不可变:
const int *p2;
int const *p3;
指针本身不可变并且指针指向的数据也不可变:
const int * const p4;
int const * const p5;
注:const只对离得近的人有用,对离得远的不管用。
const和函数形参:
const主要用在函数形参中,如果函数是一个形参,为了防止在函数内部修改指针指向的数据,就可以用const来限制。
计算某个字符在字符串出现的次数:
#include<stdio.h>
int cis(const char *s, char c) {
int n = 0;
int len = strlen(s);
for (int i = 0; i < len; i++)
{
if (s[i]==c)
{
n++;
}
}
return n;
}
int main() {
char *s = "ybbnihao";
char c = 'b';
int n = cis(s, c);
printf("%d\n",n);
return 0;
}
const 和非const 类型的转换:
非const可以赋值给const
const尽量不要覆盖非const
注:权限越多升级越难
11.2C语言随机数的生成
random和srandom
rand函数和sran函数(常用的两种)
#include<stdio.h>
#include<stdlib.h>
int main() {
for (int i = 0; i < 10; i++)
{
int a = rand();
printf("%d\n", a);
}
return 0;
}
重新播种:srand
void srand (unsigned int seed)
变量定义和初始化的时候加上这个语句:
srand((unsigned) time(NULL))
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main() {
int a;
srand((unsigned) time(NULL));
a = rand();
printf("%d\n",a);
return 0;
}
生成的随机数在一定范围:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main() {
int a;
srand((unsigned) time(NULL));
a = rand()%10+10;
printf("%d\n",a);
return 0;
}
**```
生成多个指定范围内的随机数:**
```c
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main() {
int a;
srand((unsigned)time(NULL));
for (int i = 0; i <10; i++)
{
a = rand() % 10 + 10;
printf("%d\n", a);
}
return 0;
}