产生随机数
int t = (int)time(NULL);
srand(t);
int num = rand() % 10;
利用keybd_event函数自动打印,mouse_event函数保存文件
#include <Windows.h>
void data(char str);
int main()
{
WinExec("notepad",SW_MAXIMIZE);
for (int i = 0x30; i < 0x3A; i++)
{
printf("i = %d", i);
data(i);
Sleep(1000);
}
SetCursorPos(10, 30); //指定鼠标光标位置
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
Sleep(1000);
SetCursorPos(10, 200);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
Sleep(1000);
data(VK_RETURN);
Sleep(1000);
data(0x30);
Sleep(1000);
data(VK_RETURN);
Sleep(1000);
return 0;
}
void data(char str)
{
keybd_event(str, 0, 0, 0);
keybd_event(str, 0, 2, 0);
}
实现小数转整数的四舍五入功能
double f = 2.65;
int result = f + 0.5;
printf("四舍五入后的值为:%d
", result);
查找数组中第二大值
int array[10] = { 23, 44, 21, 65, 87, 7, 33, 89, 57, 93};
int max
int smax;
max = array[0] > array[1] ? array[0] : array[1];
max = array[0] > array[1] ? array[1] : array[0];
for (int i = 2; i < 10; i++)
{
if (max < array[i])
{
smax = max;
max = array[i];
} else if ((max > array[i]) && (smax < array[i]))
{
smax = array[i];
}
}
printf("smax = %d
", smax);
幂函数的实现(以2为例)
int getPow(int n)
{
if (n == 0)
return 1;
int val = 2;
for (int i = 0; i < n; i++)
val *= 2;
return val;
}
十进制转二进制
void to_binary(unsigned int n)
{
unsigned int i = n % 2;
if (n >= 2)
to_binary(n / 2);
printf("%c", i + 0x30);
}
正整数n以内的素数和
此程序有很多地方可以优化
int sum(int n)
{
if (n == 2)
return 2;
else
{
if (isprime(n, 2))
return n + sum2(n - 1);
else
return sum2(n - 1);
}
}
int isprime(int n, int key) //判断你是否为素数,是返回1,不是返回0
{
if (n < 2)
return 0;
if (n == key)
return 1;
if (n % key == 0)
return 0;
else
return isprime(n, key + 1);
}
```
### 实现字符串拷贝函数strcpy
```c
void strcpy(char *dest, const char *src)
{
while(*dest++ = *src++);
}
```
### 实现字符串拷贝函数strncpy
```c
void strncpy(char *dest, const char *src,int n)
{
while((*dest++ = *src++) && (n--));
*(dest - 1) = 0;
}
```
### 实现文件拷贝
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[])
{
if (argc < 3)
{
return 0;
}
FILE *p1 = fopen(args[1], "rb");
FILE *p2 = fopen(args[2], "wb");
if ((p1 == NULL) || (p2 == NULL))
{
return 0;
}
char buf[1024] = { 0 };
while (!feof(p1))
{
size_t size = fread(buf, 1, sizeof(buf), p1);//由于fread与feof的差异造成fread到结尾与feof不同
fwrite(buf, 1, size, p2);//从fread读了多少字节出来,就往fwrite写多少个字节
}
fclose(p1);
fclose(p2);
return 0;
}
```
### windows和linux都可用的代码
在gcc编译时候添加参数`-DLINUX`,以下代码就可在不改变源代码情况下,同时在windows和linux下编译通过
```c
#include <stdio.h>
#ifdef LINUX
#include <unistd.h>
#else
#include <Windows.h>
#endif
int main()
{
while(1)
{
printf("a
");
#ifdef LINUX
sleep(1);
#else
Sleep(1000);
#endif
}
return 0;
}
```
### 两头堵模型
1. 初始化条件
2. strstr strchr
3. 让指针重新初始化
```c
void main()
{
char *p = " abcd ";
int ncount = 0;
int i, j;
i = 0;
j = strlen(p) -1;
while (isspace(p[i]) && p[i] != ' ')
{
i++;
}
while (isspace(p[j]) && j>0 )
{
j--;
}
ncount = j - i + 1;
printf("ncount:%d
", ncount);
}
```