博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c语言练习笔记-2

Posted on 2022-10-09 15:32  打工的外星人  阅读(18)  评论(0编辑  收藏  举报

时间戳:当前计算机的时间-计算机的起始时间(1970.1.1 0:0:0)=(xxx)秒

//猜数游戏
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu()
{
printf("**************************\n");
printf("**** 1.play 0.exit ****\n");
printf("**************************\n");
}
//RAND_MAX-32767
void game()
{
//1、生成一个随机数
int ret=0;
int guess=0;//接收猜的数字
//拿时间戳来设置随机数的生成起始点
//time_t time(time_t *timer)
//time_t
ret=rand()%100+1;//生成1-100之间的随机数
//printf("%d\n",ret);
while(1)
{
printf("请猜数字:>");
scanf("%d\n",&guess);
if(guess>ret)
{
printf("猜大了\n");
}
else if(guess<ret)
{
printf("猜小了\n");
}
else
{
printf("恭喜你猜对了!\n");
break;
}
}
}
int main () {
int input=0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("请选择>:");
scanf("%d",&input);
switch(input)
{
case 1:
game();//猜猜数游戏
break;
case 2:
printf("退出游戏\n");
break;
default:
printf("选择错误\n");
break;
}
}while(input);
return 0;
}

goto语句
反复横跳
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char input[20]={0};
//shutdown -s -t 60
//system() -执行系统命令的
system("shutdown -s -t 60");
again:
printf("请注意!你的电脑在1分钟内关机,如果输入:我是跌,就取消关机\n请输入>:");
scanf("%s",input);
if(strcmp(input,"我是爹")==0)//比较两个字符串-strcmp()
{
system("shutdown -a");
}
else
{
goto again;
}
return 0;

}


函数是什么?
在计算机科学中,子程序(英语:Subroutine,procedure,function,routine,method,subprogram,callable unit)是一个大型程序中的某部分代码,又一个或多个语句块组成,它负责完成某项特定任务,而且相比较于其他的代码,具备相对的独立性。
一般会有输入参数并有返回值,提供特定过程的封装和细节的隐藏。这些代码通常被集成为软件库。
#include<stdio.h>
int Add(int x,int y)
{
int z=0;
z=x+y;
return z;
}
int main()
{
int a=10;
int b=20;
int sum=Add(a,b);
printf("sum=%d\n",sum);
return 0;
}

c语言中函数分类:
1.库函数 www.cplusplus.com
2.自定义函数

为什么会有库函数?
1、我们知道在我们学习c语言编程的时候,总是在一个代码编完之后迫不及待的知道结果,想把我们这个结果打印到我们的屏幕上看看。这个时候我们会频繁使用一个功能;将信息按照一定的格式打印到屏幕上(printf)。
2、在编程的过程中我们会频繁的做一些字符串拷贝工作(strcpy)。
3、在编程是我们也计算,总是会计算n的k次方这样的运算(pow)。

库函数分类:
IO函数
字符串操作函数(strlen)
字符操作函数
内存操作函数
时间/日期函数
数学函数
其他库函数
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[]="bit";
char arr2[20]="********";
//bit\0结束的标志
strcpy(arr2,arr1);
printf("%s\n",arr2);
//strcpy -string copy-字符串拷贝
//strlen -string length -字符串长度有关
return 0;
}

#include<stdio.h>
#include<string.h>
int main()
{
//memset
//memory -内存 set -设置
char arr[]="hello world";
memset(arr,'*',5);
printf("%s\n",arr);
return 0;
}
https://en.cppreference.com/w/ 参考网站

自定义函数
函数的组成
ret_type fun_name(para1,*)
{
statement;//语句项(函数体交待函数的实现)
}
ret_type 返回类型
fun_name 函数名
para1 函数参数

#include<stdio.h>
//定义函数
int get_max(int x,int y)
{
if(x>y)
return x;
else
return y;
}
int main()
{
int a=10;
int b=30;
//函数的使用
int max=get_max(a,b);
printf("max=%d\n",max);
return 0;
}

#include<stdio.h>
void Swap(int x,int y)
{
int tmp=0;
x=y;
y=tmp;
}
void Swap2(int* pa,int* pb)
{
int tmp=0;
tmp=*pa;
*pa=*pb;
*pb=tmp;
}
int main()
{
int a=10;
int b=20;
printf("a=%d b=%d\n",a,b);
//Swap(a,b);
Swap2(&a,&b);
printf("a=%d b=%d\n",a,b);
return 0;
}