//1.数据类型转换
#include
void main()
{
int a = 5;
char c = 'a';
float f = 5.3;
double m = 12.65;
double result;
printf("a+c=%d\n", a + c);
printf("a+c=%c\n", a + c);
printf("f+m=%f\n", f + m);
printf("a+m=%f\n", a + m);
printf("c+m=%f\n", c + m);
result = a + c*(f + m);
printf("double=%f\n", result);
getchar();
return ;
}
//2.转义字符
#include
void main()
{
printf("换行符,用于输出换行\n");
printf("横向跳格符,使跳到下一个输出区\t");
printf("退格符\b,使当前的输出位置退一格,即输出的起始位置左移一位");
printf("回车符\r,使当前输出位置回到本行开头");
getchar();
return;
}
//3.关系和逻辑运算
#include
void main()
{
int loqic;
int a = 1;
int b = 2;
int c = 3;
loqic = a + b > c&&b <= c;
printf("loqic=%d\n", loqic);
loqic = a >= b + c || b == c;
printf("loqic=%d\n", loqic);
loqic=!(a
void main()
{
int i, j, k;
int m, n, p;
i = 8;
j = 10;
k = 12;
//自增在操作数之前
m = ++i;
printf("i=%d\n", i);//9
printf("m=%d\n", m);//9
//自减在操作数之后
n = j--;
printf("j=%d\n", j);//9
printf("n=%d\n", n);//10
getchar();
return;
//5.普通位运算
#include
void main()
{
unsigned char result;
int a, b,c, d;
a = 2;
b = 4;
c = 6;
d = 8;
//对变量进行按位与操作
result = a&c;
printf("result=%d\n", result);
//对变量进行 按位或操作
result = b | d;
printf("result=%d\n", result);
//对变量进行按位异或操作
result = a^d;
printf("result=%d\n", result);
//对变量进行取反操作
result = -a;
printf("result=%d\n", result);
getchar();
return;
}
//6.位移运算
#include
void main()
{
unsigned a, b, c, d;
int n;
a = 64;
n = 2;
//将操作数a右移(6-n)位
b = a >> (6 - n);
printf("b=%d\n", b);//4
//将操作数左移n位
c = a << n;
printf("c=%d\n", c);//256
//对操作数a进行混合位运算
d = (a >> (n - 1)) | (a << (n + 1));//544
printf("d=%d\n",d);
getchar();
return;
}
//7.字符译码
#include
void main()
{
//定义字符型变量,并给他们付初值
char c1, c2, c3, c4, c5, c6, c7;
c1 = 'c';
c2 = 'h';
c3 = 'i';
c4 = 'n';
c5 = 'e';
c6 = 's';
c7 = 'e';
//输出源码
printf("%c%c%c%c%c%c%c\n", c1, c2, c3, c4, c5, c6, c7);//chinese
//对字符进行译码运算
c1 = c1 + 6;
c2 = c2 + 6;
c3 = c3 + 6;
c4 = c4 + 6;
c5 = c5 + 6;
c6 = c6 + 6;
c7 = c7 + 6;
//输出译码结果
printf("%c%c%c%c%c%c%c", c1, c2, c3, c4, c5, c6, c7);//inotkyk
getchar();
return;
}
//8.指针操作符
#include
void main()
{
//定义一个整形指针p
int* p;
int begin, end;
begin = 10;
//给指针p赋初值
p = &begin;
//将指针指向的值传给变量end
end = *p;
printf("begin=%d\n", begin);
printf("end=%d\n", end);
//输出指针中的地址值
printf("p=%p\n",p);//是begin的地址值
printf("&begin=%p\n", &begin);
printf("*p=%d\n", *p);
getchar();
return;
}
//9.if判断语句
#include
void main()
{
int x, y, z, mid, dec;
printf("请任意输入三个整数:\n");
scanf("%d %d %d", &x, &y, &z);
if (x < y)
{
mid = x;
x = y;
y = mid;
}
if (x < z)
{
mid = x;
x = z;
z = mid;
}
if (y < z)
{
mid = y;
y = z;
z = mid;
}
printf("请输入一个整数,程序根据其正负判断输出:\n");
scanf("%d", &dec);
if (dec >= 0)
printf("最大整数为:%d\n", x);
else
printf("最小整数为:%d\n", z);
getchar();
return;
}
//10.else-if语句
#include
void main()
{
int x, y;
printf("请输入自变量x:");
scanf("%d", &x);
if (x < 6)
{
y = x - 12;
printf("x=%d,y=%d", x, y);
}
else if (x < 15)
{
y = 3 * x - 1;
printf("x=%d,y=%d", x, y);
}
else
{
y = 5 * x + 9;
printf("x=%d,y=%d", x, y);
}
getchar();
}
//11.嵌套if语句
#include
void main()
{
int sex, weight, cubage;
printf("请给出输血者的性别和体重:");
scanf("%d,%d", &sex, &weight);
if (sex >= 0) //非负数表示男性
{
if (weight >= 120)
{
cubage = 200;
printf("此人应该输血:%d毫升\n", cubage);
}
else
{
cubage = 180;
printf("此人应该输血:%d毫升\n", cubage);
}
}
else
{
if (weight >= 100)
{
cubage = 150;
printf("此人应该输血:%d毫升\n", cubage);
}
else
{
cubage = 120;
printf("此人应该输血:%d毫升\n", cubage);
}
}
getchar();
}
//12.switch语句
#include
#include
void main()
{
int num;
int indiv, ten, hundred, thousand;
int ten_thousand, hundred_thousand, place;
printf("请输入一个整数(0-999999):");
scanf("%d", &num);
if (num > 99999)
place = 6;
else if (num > 9999)
place = 5;
else if (num > 999)
place = 4;
else if (num > 99)
place = 3;
else if (num > 9)
place = 2;
else
place = 1;
printf("place=%d\n", place);
//求出num在各位上的值
hundred_thousand = num / 100000;
ten_thousand = (num - hundred_thousand * 100000) / 10000;
thousand = (num - hundred_thousand * 100000 - ten_thousand * 10000) * 1000;
hundred = (num - hundred_thousand * 100000 - ten_thousand * 10000 - thousand * 1000) / 100;
ten = (num - hundred_thousand * 100000 - ten_thousand * 10000 - thousand * 1000 - hundred * 100) / 10;
indiv = (num - hundred_thousand * 100000 - ten_thousand * 10000 - thousand * 1000 - hundred * 100 - ten * 10);
//判断变量num位数
switch (place)
{
case 1:printf("%d", indiv);
printf("\n反序数字为:");
printf("%d\n", indiv);
case 2:printf("%d,%d", ten,indiv);
printf("\n反序数字为:");
printf("%d%d\n", indiv,ten);
case 3:printf("%d,%d,%d",hundred,ten, indiv);
printf("\n反序数字为:");
printf("%d,%d,%d\n",hundred,ten, indiv);
case 4:printf("%d,%d,%d,%d",thousand,hundred,ten, indiv);
printf("\n反序数字为:");
printf("%d,%d,%d,%d\n",thousand,hundred,ten, indiv);
case 5:printf("%d,%d,%d,%d,%d",ten_thousand,thousand,hundred,ten, indiv);
printf("\n反序数字为:");
printf("%d,%d,%d,%d,%d\n", ten_thousand, thousand, hundred, ten, indiv);
case 6:printf("%d,%d,%d,%d,%d,%d",hundred_thousand, ten_thousand, thousand, hundred, ten, indiv);
printf("\n反序数字为:");
printf("%d,%d,%d,%d,%d,%d\n", hundred_thousand, ten_thousand, thousand, hundred, ten, indiv);
default:printf("Not find.\n");
break;
}
system("pause");
getchar();
}
//for语句
#include
void main()
{
int i, j, k;
//变量i从0-4,表示所画图形的第一行至第五行\
for (i = 0; i <= 4; i++)
{
//当行数为i时,空格数是i的函数,为4-i个
for (j = 0; j <= 3 - i; j++)
printf(" ");
//星号也是i的函数,为2i+1个
for (k = 0; k <= 2 * i; k++)
printf("*");
printf("\n");
}
//变量从0-3,表示所画菱形图第六行至第九行
for (i = 0; i <= 3; i++)
{
//当行数为i时,空格数是i的函数,此时为i个
for (j = 0; j <= i; j++)
printf(" ");
//星号数也是i的函数,此时为7-2i个
for (k = 0; k <= 6 - 2 * i; k++)
printf("*");
printf("\n");
}
getchar();
}
//14 while 语句
#include
#include
void main()
{
int x, y, num1, num2, temp;
printf("请输入两个正整数:\n");
scanf("%d,%d", &num1,&num2);
if (num1 > num2)
{
temp = num1;
num1 = num2;
num2 = temp;
}
x = num1;
y = num2;
while (y != 0)
{
temp = x%y;
x = y;
y = temp;
}
printf("他们的最大公约数是:%d\n", x);
printf("他们的最小公倍数是:%d\n", num1*num2/x);
getchar();
system("pause");
}
//15 do-while语句
#include
#include
void main()
{
double s, t, x;
int n;
printf("please input x:");
scanf("%lf", &x);
t = x;
n = 1;
s = x;
do
{
n = n + 2;
t = t*(-x*x) / ((float)(n)-1) / (float)(n);
s = s + t;
} while (fabs(t) >=1e-8);//fabs返回num的绝对值
printf("ain(%f)=%lf\n", x, s);
getchar();
system("pause");
}
/15 do-while语句
#include
#include
void main()
{
double s, t, x;
int n;
printf("please input x:");
scanf("%lf", &x);
t = x;
n = 1;
s = x;
do
{
n = n + 2;
t = t*(-x*x) / ((float)(n)-1) / (float)(n);
s = s + t;
} while (fabs(t) >=1e-8);//fabs返回num的绝对值
printf("ain(%f)=%lf\n", x, s);
getchar();
system("pause");
}
//16 break,continue语句
#include
void main()
{
int radius;
double area;
for (radius = 1; radius <= 10; radius++)
{
area = 3.1416*radius*radius;
if (area >= 120.0)
break;//跳出for循环
printf("square=%f\n", area);
}
printf("now radius=%d\n\n", radius - 1);
for (radius = 1; radius <= 10; radius++)
{
area = 3.1416*radius*radius;
if (area < 120.0)//如果圆面积没有超过120,则不输出,而是重新开始循环
continue;
printf("square=%f\n", area);
}
printf("now radius=%d\n", radius - 1);
}
//17 exit函数
#include
#include
void main()
{
int month;
int day;
printf("请输入月份:");
scanf("%d", &month);
switch (month )
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:day = 31;
break;
case 4:
case 6:
case 9:
case 11:day = 30;
break;
case 2:day = 28;
break;
default:exit(0);
break;
}
printf("1999.%d has %d days.\n", month, day);
getchar();
system("pause");
}
//综合例子
#include
#include
void main()
{
int i, j, num;
int p, q, flaqp, flaqq;
printf("please input a plus integer:");
scanf("%d", &num);
if (((num % 2) != 0) || (num <= 4))
printf("input data error!\n");
else
{
p = 1;
do
{
p = p + 1;
q = num - p;
flaqp = 1;
flaqq = 1;
for (i = 2; i <= (int)(floor(sqrt((double)(p)))); i++)
{
if ((p%i) == 0)
{
flaqp = 0;
break;
}
}
j = 2;
while (j <= (int)(floor(sqrt((double)(p)))))
{
if ((q%j) == 0)
flaqp = 0;
break;
}
j++;
} while (flaqp*flaqq == 0);
printf("%d=%d+%d\n", num, p, q);
}
getchar();
system("pause");
/*
floor(double num)函数,它包含在的头文件中,函数floor(double num)
的功能是返回不大于num的最大整数(表示为浮点值)
*/
}
//19 一维数组
#include
void main()
{
int i, j, min, temp;
int arr[10];
printf("please input ten integer:\n");
for (i = 0; i < 10; i++)
{
printf("arr[%d]=", i);
scanf("%d", &arr[i]);
}
printf("the arr is:");
for (i = 0; i < 10; i++)
{
printf("%d", arr[i]);
printf("\n");
}
for (i = 0; i < 9; i++)
{
min = i;
for (j = i; j < 10; j++)
if (arr[min]>arr[j])
min = j;
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
printf("\nthe result\n");
for (i = 0; i < 10; i++)
{
printf("%d", arr[i]);
printf("\n");
}
getchar();
system("pause");
}
//20 二维数组
#include
#include
void main()
{
int arr[16][16];
int i, j, k, m, n;
m = 1;
while (m == 1)
{
printf("请输入n(nn))
{
i = i + 2;
j = j - 1;
}
else
{
if (i < 1)
i = n;
if (j>n)
j = 1;
}
if (arr[i][j] == 0)
arr[i][j] = k;
else
{
i=i + 2;
j = j - 1;
arr[i][j] = k;
}
}
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
printf("%5d", arr[i][j]);
printf("\n");
}
getchar();
system("pause");
}
//21 字符数组
#include
#define MAX 100
#define LEN 80
void main()
{
char text[MAX][LEN];
int t, i, j;
for (t = 0; t < MAX; t++)
{
printf("%d:", t);
gets(text[t]);//函数gets()从stdin中读取字符串,读入的结果存放到str指向的字符数组中,一直读到接收到新行符或EOF(文件结束)为止
if (!text[t][0])
break;
}
for (i = 0; i < t; i++)
{
for (j = 0; text[i][j]; j++)
putchar(text[i][j]);//向终端输出一个字符
putchar('\n');
}
}
//22 数组初始化
#include
void main()
{
int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char arr1[13] = "How are you!";
char arr2[13] = { 'H', 'o', ' w', 'a', 'r', 'e', ' y', 'o', 'u', '!' };
int arr3[4][4] =
{
12, 18, 6, 25,
23, 10, 32, 16,
25, 63, 1, 63,
0, 0, 27, 98
};
char arr4[] = "How are you!";
int arr5[][2]=
{
{1,50},
{45,2},
{2,0},
{12,32},
{42,33},
{15,18},
};
for (int i = 0; i < 10; i++)
{
printf("%d", arr[i]);
printf("\n");
}
printf("%s\n", arr1);
printf("%s\n", arr2);
for (int i = 0; i < sizeof(arr3) / sizeof(arr3[0]); i++)//行数
{
for (int j = 0; j < 4; j++)
{
printf("arr[%d][%d] = %d ", i, j, arr3[i][j]);
}
printf("\n");
}
getchar();
}
//23 数组应用
#include
#include
void main()
{
int select;
int i, j;
int score[5][7];
int average = 0;
int sum = 0;
do
{
printf("本程序有四项功能:\n");
printf("1.根据学号查询学生成绩\n");
printf("2.根据考试号统计成绩\n");
printf("3.根据考试号和学号查询成绩\n");
printf("4.成绩录入\n");
printf("0.退出\n");
printf("请输入选择(0-4):");
scanf("%d", &select);
switch (select)
{
case 0:
printf("ok\n");
exit(0);
break;
case 1:
printf("输入学号:");
scanf("%d\n", &i);
for (j = 1; j < 7; j++)
{
printf("第%d科成绩是%d\n", j, score[i][j]);
sum += score[i][j];
}
average = sum / 6;
printf("学生的平均成绩是%d\n", average);
break;
case 2:
printf("输入学号:");
scanf("%d\n", &i);
for (j = 1; j < 5; j++)
{
printf("第%d学号学生本科成绩是%d\n", i, score[i][j]);
sum += score[i][j];
}
average = sum / 4;
printf("本科平均成绩是%d\n", average);
break;
case 3:
printf("输入学号和考试号:");
scanf("%d %d\n", &i,&j);
printf("第%d学号学生第%d科成绩是%d\n", i,j, score[i][j]);
break;
case 4:
printf("请输入成绩\n");
for (i = 1; i < 5; i++)
for (j = 1; j < 7; j++)
scanf("%d\n", &score[i][j]);
break;
default:
break;
}
} while (1);
getchar();
system("pause");
}
//24.函数值的调用
#include
int square(int x);
int cube(int y);
void main()
{
int m = 12;
int n = 4;
printf("%d %d\n", square(m), m);
printf("%d %d\n", cube(n), n);
getchar();
return;
}
int square(int x)
{
x = x*x;
return x;
}
int cube(int y)
{
y = y*y*y;
return y;
}
//25.函数的引用调用
#include
void swap(int*x, int* y);
void main()
{
int i, j;
i = 12;
j = 36;
printf("i and j before swapping:%d %d\n", i, j);
swap(&i, &j);
printf("i and j after swapping:%d %d\n", i, j);
getchar();
}
void swap(int* x, int* y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
//26 数组函数的调用
#include
#define N 3
//转置函数声明
void convert(int element[N][N]);
void main()
{
int arr[N][N];
int i, j;
printf("输入数组元素:\n");
for (int i = 0; i < N; i++)
for (j = 0; j < N; j++)
scanf("%d", &arr[i][j]);
printf("\n数组是:\n");
for (int i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%5d", arr[i][j]);
printf("\n");
}
//对数组进行转置工作
convert(arr);
printf("转置数组是:\n");
for (int i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%5d", arr[i][j]);
printf("\n");
}
getchar();
system("pause");
return;
}
//转置函数定义
void convert(int element[N][N])
{
int i, j, t;
for (int i = 0; i < N; i++)
{
for (j = i + 1; j < N; j++)
{
t = element[i][j];
element[i][j] = element[j][i];
element[j][i] = t;
}
}
}
//命令行变元
#include
#include
#include
#include
#include
void main(int argc,char* argv[])
{
int disp, count;
if (argc < 2)
{
printf("you must enter the length of the count \n");
printf("on the command line try again\n");
exit(1);
}
if (argc == 3 && !strcmp(argv[2], "display"))
disp = 1;
else
disp = 0;
for (count = atoi(argv[1]); count;--count)
if (disp)
printf("%d\n", count);
putchar('\a');
printf("down");
getchar();
system("pause");
return;
/*
函数atoi()把str指向的串转换为整型值,串中必须含有合法的整型值,否则返回的值无定义,
串中的整数内容可由任何不是该整数的一部分的字符终止,如空白符,标点符或字符等
也就是说,用123.23调用atoi()时,返回整型值123,忽略0.23
在程序中,如果串display作为命令行的第二个变元,则减量过程显示在屏幕上
*/
}
//28 函数的返回值
/*
1.函数的返回值是通过函数中的return语句获得,return语句将被调用函数中的一个确定值带回主函数中,一个函数中
可以有一个以上的return语句,执行到哪一个return语句,哪一个语句起作用
2.函数的返回值应当属于某一个确定的类型,应当在定义时指定函数值的类型,C语言规定,凡不加类型说明的函数,一律自动按整数类型处理
3.如果函数值的类型和return语句中的表达式不一致,则以函数类型为准
4.如果被调用函数中没有return语句,并不表示函数不带回值,只是不带回有用的值,带回的是一个不确定的值,可以用void定义无类型
*/
#include
int find_substr(char* s1, char* s2);
void main()
{
if (find_substr("C is fun ", "is") != -1)
printf("substring is found\n");
getchar();
return;
}
//定义子函数
int find_substr(char* s1, char* s2)
{
int t;
char* p, *p2;
for (t = 0; s1[t]; t++)
{
p = &s1[t];
p2 = s2;
while (*p2&&*p2 == *p)
{
p++;
p2++;
}
if (!*p2)
return t;
}
return -1;
}
//函数的嵌套调用
#include
#include
//定义函数f,以实现x^3-8*x^2+12*x-30=0;
float f(float x)
{
float y;
y = ((x - 8.0)*x + 12.0)*x - 30.0;
return y;
}
//定义函数xpoint, 求出弦与x轴的焦点横坐标
float xpoint(float x1, float x2)
{
float y;
y = (x1*f(x2) - x2*f(x1)) / (f(x2)) - f(x1));
return y;
}
//定义函数root,求解区间(x1,x2)的实根
float root(float x1, float x2)
{
float x, y, y1;
y1 = f(x1);
do
{
x = xpoint(x1, x2);
y = f(x);
if (y*y1 > 0)
{
y1 = y;
x1 = x;
}
else
x2 = x;
} while (fabs(y) >= 0.0001);
return x;
}
void main()
{
float x1, x2, f1, f2, x;
do
{
printf("please input x1 x2:\n");
scanf("%f,%f", &x1, &x2);
f1 = f(x1);
f2 = f(x2);
} while (f1*f2 > 0);
x = root(x1, x2);
printf("A root of equation is %9.6f\n", x);
getchar();
system("pause");
return;
}
//30 函数的递归调用
#include
void convert(int n)
{
int i;
if ((i = n / 10) != 0)
convert(i);
putchar(n % 10 + '0');
}
void main()
{
int number;
printf("输入整数:");
scanf("%d", &number);
printf("输出是:");
if (number < 0)
{
putchar('-');
number = -number;
}
convert(number);
putchar('\n');
}
//局部和全局变量
#include
int count;
void func1();
void func2();
void main()
{
count =100;
func1();
getchar();
}
void func1()
{
int temp;
temp = count;
func2();
printf("count is %d\n", count);
func2();
}
void func2()
{
int count;
for (count = 1; count < 20; count++)
printf(".");
printf("\n");
}
//变量的存储类别
#include
int sum_day(int month, int day);
int leap(int year);
void main()
{
int year, month, day;
int days;
printf("请输入日期(年,月,日)");
scanf("%d %d %d", &year, &month, &day);
days = sum_day(month, day);
if (leap(year) && month >= 3)
days = days + 1;
printf("是该年的第%d天.\n",days);
getchar();
system("pause");
}
static int day_tab[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int sum_day(int month, int day)
{
int i;
for (i = 1; i < month; i++)
day = day + day_tab[i];
return day;
}
int leap(int year)
{
int leap;
leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
return leap;
}
//综合实例
#include
void head1();
void head2();
void head3();
int count;
void main()
{
register int index;//定义为主函数寄存器变量,这样我们调用index时候会节省很多时间
head1();
head2();
head3();
for (index = 8; index > 0; index--)
{
int stuff;
for (stuff = 0; stuff <= 6; stuff++)
{
printf("%d", stuff);
}
printf("index is now %d\n", index);
}
getchar();
return;
}
int counter;
void head1()
{
int index;
index = 23;
printf("the header value is %d\n", index);
}
void head2()
{
int count;
count = 53;
printf("the header2 value is %d\n", count);
counter = 77;
}
void head3()
{
printf("the header3 value is %d\n", counter);
}
//综合实例
#include
#define M 5
#define N 10
float score[N][M];
float a_stu[N], a_cor[M];
void input_stu();
void avr_stu();
void avr_cor();
float highest(int* r, int* c);
float s_diff();
void main()
{
int i, j, r, c;
float h;
r = 0;
c = 1;
intpu_stu();
avr_stu();
avr_cor();
printf("\n 序号 课程1 课程2 课程3 课程4 课程5 平均分");
for (i = 0; i < N; i++)
{
printf("\n no%2d", i + 1);
for (j = 0; j < M; j++)
{
printf("%8.2f", score[i][j]);
}
printf("%8.2f", a_stu[i]);
}
printf("\n课平均");
for (j = 0; j < M; j++)
printf("%8.2f", a_cor[j]);
h = hichest(&r, &c);
printf("\n\n最高分%8.2f是%d 号学生的第%d门课\n", h, r, c);
printf("方差%8.2f\n", s_diff());
getchar();
system("pause");
return;
}
void input_stu()
{
int i, j;
for (i = 0; i < N; i++)
{
printf("请输入学生%2d的五个成绩:\n", i + 1);
for (j = 0; j < M; j++)
scanf("%f", &score[i][j]);
}
}
void avr_stu()
{
int i, j;
float s;
for (i = 0; i < N; i++)
{
s = 0;
for (j = 0; j < M; j++)
s = s + score[i][j];
a_stu[i] = s / M;
}
}
void avr_cor()
{
int i, j;
float s;
for (j = 0; j < M; j++)
{
s = 0;
for (i = 0; i < N; i++)
s = s + score[i][j];
a_cor[j] = s / (float)N;
}
}
float highest(int* r, int*c)
{
float high;
int i, j;
high = score[0][0];
for (i = 0; i < N;i++)
for (j = 0; j < M;j++)
if (score[i][j]>high)
{
high = score[i][j];
*r = i + 1;
*c = j + 1;
}
return high;
}
float s_diff()
{
int i;
float sumx, sumn;
sumx = 0.0;
sumn = 0.0;
for (i = 0; i < N; i++)
{
sumx = sumx + a_stu[i] * a_stu[i];
sumn = sumn + a_stu[i];
}
return (sumx / N - (sumn / N)*(sumn / N));
}
//变量的指针
#include
void swap(int* pt1, int* pt2);
void exchange(int* q1, int* q2, int* q3);
void main()
{
int x, y, z, *p1, *p2, *p3;
printf("请输入三个整数:");
scanf("%d,%d,%d", &x, &y, &z);
p1 = &x;
p2 = &y;
p3 = &z;
exchange(p1, p2, p3);
printf("按大小排序后的三个整数为:");
printf("%d,%d,%d\n", x, y, z);
}
void swap(int* pt1, int* pt2)
{
int p;
p = *pt1;
*pt1 = *pt2;
*pt2 = p;
}
void exchange(int* q1, int* q2, int* q3)
{
if (*q1 < *q2) swap(q1, q2);
if (*q1 < *q3) swap(q1, q3);
if (*q2 < *q3)swap(q2, q3);
}
//一维数组指针
/*
一维数组其数组名字就是数组在内存中的首地址,若再定义一个指针变量,并将数组的首地址
传给指针变量,则该指针就指向这个一维数组.数组名是数组的首地址,也是数组的指针.对数组的引用
既可以用传统的数组元素的下标法,也可以使用指针的表示方法
*/
#include
void inv(int* x, int n);
void main()
{
int i;
int arr[10] = { 1, 3, 9, 11, 0, 8, 5, 6, 14, 98 };
printf("原数组是:\n");
for (int i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
inv(arr, 10);
printf("按相反次序存放后的数组为:\n");
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
getchar();
}
void inv(int* x, int n)
{
int* p, *i, *j;
int t;
int m = (n - 1) / 2;
i = x;
j = x + n - 1;
p = x + m;
for (; i <= p; i++, j--)
{
t = *i;
*i = *j;
*j = t;
}
}
//二维数组指针
#include
void main()
{
int num;
void average(float* point, int n);
void search(float(*point)[4], int n);
static float score[4][4] = { { 76, 90, 92, 87 }, { 68, 78, 69, 94 },
{ 89, 82, 81, 60 }, { 81, 68, 60, 97 } };
printf("班级的总平均分:");
average(*score, 16);
printf("请输入学生的学号(0-3):");
scanf("%d", &num);
search(score, num);
getchar();
system("pause");
}
void average(float* point, int n)
{
float *p_end;
float aver;
float sum = 0;
p_end = point + n - 1;
for (; point <= p_end; point++)
{
sum = sum + (*point);
}
aver = sum / n;
printf("%5.2f\n", aver);
}
void search(float(*point)[4], int n)
{
int i;
for (i = 0; i < 4; i++)
{
printf("%5.2f\n", *(*(point + n) + i));
}
printf("\n");
}
//字符串指针
#include
//将字符串a复制到字符串b
void main()
{
int i;
char a[] = "I am a student.";
char b[20];
char* p1, *p2;
p1 = a;//将数组a的首地址赋给字符型指针p1
p2 = b;
for (; *p1 != '\0'; p1++, p2++)
{
*p2 = *p1;
}
*p2 = '\0';
printf("string a is: %s\n", a);
printf("string b is:");
for (i = 0; b[i] != '\0'; i++)
{
printf("%c", b[i]);
}
printf("\n");
getchar();
}
//函数指针
/*
(1)指向函数的指针变量的一般定义形式为:
数据类型标识符(*指针变量名)();
数据类型标识符是指向函数返回值的类型
(2)可以通过函数名调用函数,也可以通过函数指针调用(即用指向函数的指针变量
表示)
(3)在给函数指针变量赋值时,只需要给出函数名而不必给出参数
(4)用函数指针变量调用函数时,只需要将(*point)代替函数名即可,在
(*point)之后的括弧中根据需要写上实参
(5)对于指向函数的指针变量,point++等运算都是无意义的
*/
#include
#include
void check(char* a, char* b, int(*cmp)(const char*, const char*));
void main()
{
char s1[80];
char s2[80];
int(*p)(const char*, const char*);//定义一个函数指针
p = strcmp;
/*
函数strcmp包含在头文件中,功能是
比较他的两个参数是否相等
*/
printf("输入两个字符串:\n");
gets(s1);
gets(s2);
check(s1, s2, p);
getchar();
}
void check(char* a, char* b, int(*cmp)(const char*, const char*))
{
printf("测试是否相等\n");
if (!(*cmp)(a, b))
printf("结果:相等\n");
else
printf("结果:不想等\n");
}
//指针数组
//一个数组,其元素全为指针类型数据,称为指针数组
#include
#include
#include
void main()
{
int binary(char*ptr[], char*str, int n);
void insert(char* ptr[], char* str, int n, int i);
char* temp, *ptr1[6];
int i;
printf("请为字符型指针数组赋值:\n");
for (i = 0; i < 5; i++)
{
ptr1[i] = (char*)malloc(20);//为指针分配地址
gets(ptr1[i]);//输入字符串
}
ptr1[5] = (char*)malloc(20);
printf("\n");
printf("ariginal string:\n");
for (i = 0; i < 5; i++)
printf("%s\n", ptr1[i]);
printf("ninput search string :\n");
temp = (char*)malloc(20);
gets(temp);
i = binary(ptr1, temp, 5);
printf("i=%d\n", i);
insert(ptr1, temp, 5, i);
printf("output string:\n");
for (i = 0; i < 6; i++)
printf("%s\n", ptr1[i]);
}
int binary(char*ptr[], char*str, int n)
{
//折半查找插入位置
int hig, low, mid;
low = 0;
hig = n - 1;
if (strcmp(str, ptr[0]) < 0)
return 0;
if (strcmp(str, ptr[hig])>0)
return n;
while (low <= hig)
{
mid = (low + hig) / 2;
if (strcmp(str, ptr[mid]) < 0)
hig = mid - 1;
else if (strcmp(str, ptr[mid])>0)
low = mid + 1;
else
return mid;
}
return low;
}
void insert(char* ptr[], char* str, int n, int i)
{
int j;
for (j = n; j > i; j--)
strcpy(ptr[j], ptr[j - 1]);
strcpy(ptr[i], str);
}
//二维数组
//用指向指针的指针变量访问一维和二维数组
#include
#include
void main()
{
int a[10], b[3][4];
int*p1, *p2, **p3;
int i, j;
printf("请输入一维数组(10个元素):\n");
for (i = 0; i < 10; i++)
scanf("%d", &a[i]);
printf("请输入二维数组(三行四列):\n");
for (i = 0; i < 3;i++)
for (j = 0; j < 4; j++)
scanf("%d", &b[i][j]);
printf("\n");
//分别给一维指针变量p1和二维指针变量p3赋值
for (p1 = a, p3 = &p1, i = 0; i < 10; i++)
printf("%4d", *(*p3 + i));//用二维指针变量输出一维数组
printf("\n");
for (p1 = a; p1 - a < 10; p1++)//用二维指针变量输出一维数组
{
p3 = &p1;
printf("%4d", **p3);
}
printf("\n");
for (i = 0; i < 3; i++)
{
p2 = b[i];
p3 = &p2;
for (j = 0; j < 4; j++)
printf("%4d", *(*p3 + j));
printf("\n");
}
for (i = 0; i < 3; i++)
{
p2 = b[i];
for (p2 = b[i]; p2 - b[i] < 4; p2++)
{
p3 = &p2;
printf("%4d", **p3);
}
printf("\n");
}
getchar();
system("pause");
}
//指针的初始化
#include
#include
int search(char* p[], char* name);
char* names[] = {
"herb",
"rex",
"dennis",
"john",
"NULL"
};
void main()
{
if (search(names, "herb") != -1)
printf("herb is in list\n");
if (search(names, "mary") == -1)
printf("mary not found\n");
}
int search(char* p[], char* name)
{
register int t;
for (t = 0; p[t];++t)
if (!strcmp(p[t], name))
return t;
return -1;
}
//综合实例
#include
void avscc(float* psco, float* pave);
void avcour5(char* pcou, float* psco);
void fail2(char* pcou, int* pnum, float* psco, float* pave);
void excellence(char* pcou, int *pnum, float* psco, float*pave);
void main()
{
int i, j, *pnum, num[4];
float score[4][5], aver[4], *psco, *pave;
char course[5][10], *pcou;
printf("请按行输入5门功课的名称:\n");
pcou = course[0];
for (i = 0; i < 5; i++)
scanf("%s", pcou + 10 * i);
printf("请按下面的格式输入四个学生的学号和各科成绩:\n");
printf("学号");
for (i = 0; i < 5; i++)
printf(",%s", pcou + 10 * i);
printf("\n");
psco = &score[0][0];
pnum = &num[0];
for (i = 0; i < 4; i++)
{
scanf("%d", pnum + i);
for (j = 0; j < 5; j++)
scanf(",%f", psco + 5 * i + j);
}
pave = &aver[0];
printf("\n\n");
avsco(psco, pave);
avcour5(pcou, psco);
printf("\n\n");
fail2(pcou, pnum, psco, pave);
printf("\n\n");
excellence(pcou, pnum, psco, pave);
}
//求每个学生平均成绩
void avscc(float* psco, float* pave)
{
int i, j;
float sum, average;
for (i = 0; i < 4; i++)
{
sum = 0.0;
for (j = 0; j < 5; j++)//j代课程序号,表示第j门
sum = sum + (*(psco + 5 * i + j));//累计每个学生的各科成绩
average = sum / 5;
*(pave) = average;
}
}
void avcour5(char* pcou, float* psco)
{
int i;
float sum, average5;
sum = 0.0;
for (i = 0; i < 4; i++)
sum = sum + (*(psco + 5 * i + 4));
average5 = sum / 4;
printf("第五门课%s的平均成绩为%5.2f\n", pcou, average5);
}
void fail2(char* pcou, int* pnum, float* psco, float* pave)
{
int i, j, k, label;
printf("===两门以上课程不及格的学生===\n");
printf("学号");
for (i = 0; i, 5; i++)
printf("%-8s", pcou + 10 * i);
printf("平均分\n");
for (i = 0; i < 4; i++)
{
label = 0;
for (j = 0; j < 5;j++)
if (*(psco + 5 * i + j) < 60.0)
label++;
if (label >= 2)
{
printf("%-8d", *(pnum + i));
for (k = 0; k < 5; k++)
printf("%-8.2f", *(psco + 5 * i + k));
printf("%-8.2f", *(pave + i));
}
}
}
void excellence(char* pcou, int *pnum, float* psco, float*pave)
{
int i, j, k, label;
printf("===成绩优秀学生===\n");
printf("学号");
for (i = 0; i, 5; i++)
printf("%-8s", pcou + 10 * i);
printf("平均分\n");
for (i = 0; i < 4; i++)
{
label = 0;
for (j = 0; j < 5; j++)
if (*(psco + 5 * i + j) >=85.0)
label++;
if (label >= 5||(*(pnum+i)>=90))
{
printf("%-8d", *(pnum + i));
for (k = 0; k < 5; k++)
printf("%-8.2f", *(psco + 5 * i + k));
printf("%-8.2f", *(pave + i));
}
}
}
//结构体
#include
#include
//计算天数
struct
{
int year;
int month;
int day;
}data;
void main()
{
int days;
printf("请输入日期(年,月,日):");
scanf("%d, %d, %d", &data.year, &data.month, &data.day);
switch (data.month)
{
case 1:days = data.day;
break;
case 2:days = data.day - 31;
break;
case 3:days = data.day + 59;
break;
case 4:days = data.day + 90;
break;
case 5:days = data.day + 120;
break;
case 6:days = data.day + 151;
break;
case 7:days = data.day + 181;
break;
case 8:days = data.day + 212;
break;
case 9:days = data.day + 243;
break;
case 10:days = data.day + 273;
break;
case 11:days = data.day + 304;
break;
case 12:days = data.day + 334;
break;
}
if (data.year % 4 == 0 && data.year % 100 != 0 || data.year % 400 == 0)
{
if (data.month >= 3)
days = days + 1;
}
printf("%d月%d日是%d年的第%d天.\n", data.month, data.day, data.year, days);
getchar();
system("pause");
}
//结构体数组
#include
struct student
{
char number[6];
char name[6];
int score[3];
}stu[2];//定义一个结构体,并同时声明一个数组变量
void output(struct student stu[2]);
void main()
{
int i, j;
for (i = 0; i<2; i++)
{
printf("请输入学生%d的成绩:\n", i + 1);
printf("学号:");
scanf("%s", stu[i].number);
for (j = 0; j<3; j++)
{
printf("成绩%d.", j + 1);
scanf("%d", &stu[i].score[j]);
}
printf("\n");
}
output(stu);
getchar();
system("pause");
}
void output(struct student stu[2])
{
int i, j;
printf("学号,姓名,成绩1,成绩2,成绩3\n");
for (i = 0; i < 2; i++)
{
printf("%-6s%-6s", stu[i].number, stu[i].name);
for (j = 0; j < 3; j++)
printf("%-8d", stu[i].score[j]);
printf("\n");
}
}
//结构体指针变量
#include
#include
void main()
{
struct student
{
long num;
char name[30];
char sex[10];
float score;
};
struct student stu;
struct student *p;
p = &stu;
stu.num = 97032;
strcpy(stu.name, "小明");
strcpy(stu.sex, "男");
stu.score = 98.5;
//通过结构体变量输出
printf("学号: %ld\n姓名: %s\n性别: %s\n分数: %4.2f\n",stu.num,stu.name,stu.sex,stu.score);
printf("\n");
//通过结构体指针输出
printf("学号: %ld\n姓名: %s\n性别: %s\n分数: %4.2f\n", (*p).num, (*p).name, (*p).sex, (*p).score);
}
//结构体指针数组
#include
struct student
{
long num;
char name[20];
char sex;
int age;
};
struct student stu[4] =
{
{ 97032, "xiao ming", 'M', 20 },
{ 97033, "xiao wang", 'M', 20 },
{ 97034, "xiao tong", 'M', 21 },
{ 97035, "xiao shui", 'F', 18 },
};
void main()
{
struct student *p;
printf("学号 姓名 性别 年龄\n");
for (p = stu; p < stu + 4; p++)//p指向结构体数组
printf("%-8ld%-12s%-10c%-3d\n", p->num, p->name, p->sex, p->age);
}
//共用体变量
//共用体常用于需要频繁进行类型转换的场合,程序可以使用联合中的数据
//共用体变量所占用的内存长度等于最长的成员长度
#include
union data
{
int a;
float b;
double c;
char d;
}exa;
void main()
{
exa.a = 6; printf("%d\n", exa.a);
exa.c = 67.2; printf("%5.1f\n", exa.c);
exa.d = 'W'; exa.b = 34.2;
printf("%5.1f, %c\r ", exa.b,exa.d);
}
//枚举
/*
如果一个变量只有几种可能的值,那么便可以定义为枚举类型
所谓枚举,就是将变量的值一一列举出来,变量的值只限于列举出来的值的范围内
关键字enum表示开始定义
*/
//读写字符
/*
getchar()函数等待击键,发生击键后将读入值返回,并自动把击键结果显示在屏幕上,putchar()把传入的
字符写在屏幕的当前光标处
*/
#include
#include
void main()
{
char ch;
printf("please enter some text(input a point to quit).\n");
do{
ch = getchar();
if (islower(ch))//查看ch是否为小写字符
ch = toupper(ch);//函数功能:在ch为字母时,返回等价的大写字母,否则返回的ch值不变
else
ch = tolower(ch);//函数功能:在ch为字母时,返回等价的小写字母,否则返回的ch值不变
putchar(ch);
} while (ch != '.');
}
//读写字符串
/*gets()和puts()
gets()是将键盘输入的一个字符串读入,把读入结果放到指针变元指向的地址,用户键入字符直到回车,函数
读入键入的字符,忽略回车符,然后在读入串的尾部自动加上null终止符
puts()是把变元串写到显示屏上,然后再写一个新的行符
*/
#include
#include
#include
char* dic[][40] =
{
"luater", "A bright shine on the surface",
"disgrass", "Loss of honor and respect",
"glamour", "Strong attraction",
"tomb", "The place where a dead person is buried",
"garbage", "Unwanted or spoiled food",
"bliss", "Great happiness or joy",
"commend", "Speak favorably of",
" ", " "//null end the list
};
void main()
{
char word[80], ch;
char** point;
do{
puts("please enter word:");
scanf("%s", word);
point = (char**)dic;
do{
if (!strcmp(*point, word))
{
puts("The meaning of the word is:");
puts(*(point + 1));
break;
}
if (!strcmp(*point, word))
break;
point = point + 2;
} while (*point);
if (!*point)
puts("The word is not in dictionary");
printf("Another? (y/n):");
scanf("%c%*c", &ch);//%*c表示,scanf()读入该区域但不向任何变量赋值
} while (toupper(ch) != 'N');
}
//格式化输出函数
#include
void main()
{
unsigned number;
double item = 1.23456;
for (number = 8; number < 16; number++)
{
printf("%o ", number); //八进制输出number
printf("%x ", number);//十进制(小写)输出
printf("%x\n", number);//十进制(大写)输出number
}
printf("\n");
printf("%p\n\n", &item);
printf("%f\n", item);
printf("%8.2f\n", item);//总域宽为8,小数部分占2
printf("%-8.2f\n", item);//域中左对齐输出(默认右对齐)
}
//格式化输入函数
#include
void main()
{
int i, j, k;
char str[80];
char* p;
scanf("%d %o %x", &i, &j, &k);
printf("%d %d %d\n\n", i, j, k);
printf("Enter a string:");
scanf("%s", str);
printf("Here is your string :%s\n\n", str);
printf("Enter an address:");
scanf("%p", &p);
printf("Value at location %p is %c.\n", p, *p);
}
//文件
#include
#include
void main()
{
FILE* fp;
char ch, filename[10];
printf("Please input the name of file:");
scanf("%s", filename);
if ((fp = fopen(filename, "r")) == NULL)
{
printf("Cannot open the file.\n");
exit(0);
}
fclose(fp);
}
//fputc(),fgetc()
#include
#include
#include
void main()
{
FILE *fp;
char str[100];
int i;
if ((fp = fopen("flie.txt", "w")) == NULL)
{
printf("无法打开文件\n");
exit(0);
}
printf("请输入一个字符串:\n");
gets(str);
//将字符串中的小写字符转换成大写字符,直到遇到.为止
for (i = 0; str[i] != '.'; i++)
{
if (str[i] >= 'a'&&str[i] <= 'z')
str[i] = str[i] - 32;
fputc(str[i], fp);//将转换后的字符存入文件
}
fcolse(fp);
fp = fopen("file.txt", "r");
for (i = 0; str[i] != '.'; i++)
str[i] = fgetc(fp);
printf("%s\n", str);
fclose(fp);
}
//函数rewind()
//重置文件的位置,将其置到函数变元所指定的文件的开头部分
#include
#include
#include
void main()
{
char str[80];
FILE* fp;
if ((fp = fopen("test.txt", "w")) == NULL)
{
printf("Cannot open file.\n");
exit(0);
}
do{
printf("Please enter a string:\n");
gets(str);
strcat(str, "\n");
fputs(str, fp);
} while (*str != '\n');
//从文件中读出字符串,并将他们展示出来
rewind(fp);
while (!feof(fp))
{
fgets(str, 79, fp);
printf(str);
}
fclose(fp);
}
//fread(),fwrite()
//读写长于一个字节的数据类型
#include
#include
void main()
{
FILE* fp;
int i = 156;
long l = 9701076L;
double d = 3.456;
if ((fp = fopen("test", "w")) == NULL)
{
printf("不能打开文件.\n");
exit(0);
}
//通过fwrite将数据写入文件
fwrite(&i, sizeof(int), l, fp);
fwrite(&l, sizeof(long), l, fp);
fwrite(&d, sizeof(double), l, fp);
rewind(fp);
//通过fread将数据读出文件
freaf(&i, sizeof(int), l, fp);
freaf(&l, sizeof(long), l, fp);
fread(&d, sizeof(double), l, fp);
printf("i=%d\n", i);
printf("l=%ld\n", l);
printf("d=%f\n", d);
fclose(fp);
}
//fprintf(),fscanf()
/*
本例以写的方式打开文件,从键盘输入数据并存储到文件中去,存储完毕后将文件关闭,
再以读写方式打开文件,将数据从文件中读出,并在屏幕上输出,最后关闭文件
*/
#include
#include
#include
void main()
{
FILE* fp;
char str[80];
int i;
if ((fp = fopen("test", "w")) == NULL)
{
printf("不能打开文件.\n");
exit(0);
}
printf("Please enter a string and a number:\n");
fscanf(stdin, "%s %d", str, &i);//参数stdin表示从键盘读入
fprintf(fp, "%s %d", str, i);
fclose(fp);
if ((fp = fopen("test", "r")) == NULL)
{
printf("不能打开文件:\n");
exit(0);
}
fscanf(fp, "%s %d", str, &i);
fscanf(stdout , "%s %d", str, &i);//参数stdout表示写向屏幕
fclose(fp);
}
//随机存取
//读写完上一个字符后,并不一定要读写其后续的字符,而是可以读写文件中任意所需字符
#include
void main(int argc,char* argv[])
{
FILE* fp;
if (argc != 3)
{
printf("缺少字节位置,无法进行操作.\n");
exit(0);
}
if ((fp = fopen(argv[1], "rb")) == NULL)
{
printf("无法打开文件.\n");
exit(0);
}
if (fseek(fp, atol(argv[2]), 0))
{
printf("寻找出现错误.\n");
exit(0);
}
printf("在%ld处的字符是%c.\n", atol(argv[2]), getc(fp));
fclose(fp);
}
//错误处理
#include
#include
#define TAB_NUM 8
#define IN 0
#define OUT 1
void error(int e)
{
if (e == IN)
{
printf("输入错误.\n");
}
else
printf("输出错误.\n");
exit(1);
}
void main(int argc,char* argv[])
{
FILE* in, *out;
int tab, i;
char ch;
if (argc != 3)
{
printf("用法错误.\n");
exit(1);
}
if ((out = fopen(argv[1], "wb")) == NULL);
{
printf("不能打开输入文件%s.\n", argv[1]);
exit(1);
}
if ((out = fopen(argv[2], "wb")) == NULL)
{
printf("不能打开输出文件%s.\n", argv[2]);
}
tab = 0;
do{
ch = getc(in);
if (ferror(in))
error(IN);
if (ch == '\t')
{
for (i = tab; i < 8; i++)
{
putc(' ', out);
if (ferror(out))
error(OUT);
}
tab = 0;
}
else
{
putc(ch, out);
if (ferror(out))
error(OUT);
tab++;
if (tab == TAB_NUM)
tab = 0;
if (ch == '\n' || ch == '\r')
tab = 0;
}
} while (!feof(in));
fclose(in);
fclose(out);
}
//综合实例
#include
#include
#define MAX 100
struct addr
{
char name[20];
char street[40];
char city[20];
char state[4];
unsigned long zip;
}addr_list[MAX];
void init_list(void);
void enter(void);
void dele(void);
void list(void);
void save(void);
void load(void);
int menu_select(void);
int find_free(void);
void mian()
{
char choice;
init_list();
for (;;)
{
choice = menu_select();
switch (choice)
{
case 1:enter();
break;
case 2:dele();
break;
case 3:list();
break;
case 4:save();
break;
case 5:load();
break;
case 6:exit(0);
break;
}
}
}
void init_list(void)
{
register int t;
for (t = 0; t < MAX; t++)
addr_list[t].name[0] = '\0';
}
void enter(void)
{
int slot;
char str[80];
slot = find_free();
if (slot == -1)
printf("\nList Full");
printf("Enter name:");
gets(addr_list[slot].name);
printf("Enter street:");
gets(addr_list[slot].street);
printf("Enter city:");
gets(addr_list[slot].city);
printf("Enter state:");
gets(addr_list[slot].state);
printf("Enter zip:");
gets(str);
addr_list[slot].zip = strtoul(str, '\0', 10);
}
void dele(void)
{
register int slot;
char str[80];
printf("Enter record #:");
gets(str);
slot = atoi(str);
if (slot >= 0 && slot < MAX)
addr_list[slot].name[0] = '\0';
}
void list(void)
{
register int t;
for (t = 0; t < MAX; t++)
{
if (addr_list[t].name[0])
{
printf("%s\n", addr_list[t].name);
printf("%s\n", addr_list[t].street);
printf("%s\n", addr_list[t].city);
printf("%s\n", addr_list[t].state);
printf("%s\n", addr_list[t].zip);
}
}
printf("\n\n");
}
void save(void)
{
FILE*fp;
register int i;
if ((fp = fopen("maillist", "wb")) == NULL)
printf("Cannot open file.\n");
for (i = 0; i < MAX;i++)
if (*addr_list[i].name)
if (fwrite(&addr_list[i], sizeof(struct addr), 1, fp) != 1)
printf("File write error.\n");
fclose(fp);
}
void load(void)
{
FILE *fp;
register int i;
if ((fp = fopen("maillist", "rb")) == NULL)
printf("Cannot open file.\n");
init_list();
for (i = 0; i < MAX;i++)
if (fread(&addr_list[i], sizeof(struct addr), 1, fp) != 1)
{
if (feof(fp))
break;
printf("File read error.\n");
}
fclose(fp);
}
int menu_select(void)
{
char str[80];
int c;
printf("1.Enter a name\n");
printf("2.Delete a name\n");
printf("3.List the file\n");
printf("4.save the file\n");
printf("6.Load the file\n");
printf("6.Quit\n");
do{
printf("\nEnter your choice:");
gets(str);
c = atoi(str);
} while (c<0 || c>6);
return c;
}
int find_free(void)
{
register int t;
for (t = 0; addr_list[t].name[0] && t < MAX; t++);
if (t == MAX)
return -1;
return t;
}
//常用时间函数
//#include
#include
int main()
{
struct tm* local;
time_t tm;
tm = time(NULL);
local = localtime(&tm);
printf("Local time and date:%s\n", asctime(local));
local = gmtime(&tm);
printf("UTC time and date:%s\n", asctime(local));
return 0;
}
//转换函数
#include
#include
int main()
{
char num1[80], num2[80];
double sum1;
int sum2;
long sum3;
printf("Enter first:");
gets(num1);
printf("Enter second:");
gets(num2);
sum1 = atof(num1) + atof(num2);
printf("The sum is :%f\n", sum1);
printf("Enter three:");
gets(num1);
printf("Enter four:");
gets(num2);
sum2 = atof(num1) + atof(num2);
printf("The sum is :%d\n", sum2);
printf("Enter five:");
gets(num1);
printf("Enter six:");
gets(num2);
sum3 = atof(num1) + atof(num2);
printf("The sum is :%d\n", sum3);
}
//查找函数
#include
#include
#include
char *alpha = "abcdefghigkmnopqrstuvwxyz";
int comp(const void* ch, const void* s);
int main()
{
char ch;
char* p;
printf("Enter a character:");
ch = getchar();
ch = tolower(ch);//将变元ch转换成小写字母
p = (char*)bsearch(&ch, alpha, 26, 1, comp);
if (p)
printf("%c is in alphabet\n", *p);
else
printf("is not in alphabet\n");
return 0;
}
int comp(const void *ch, const void *s)
{
return *(char*)ch - *(char*)s;
}
//跳转函数
#include
#include
jmp_buf ebuf; //类型在中定义
void fun(void);
int main()
{
int i;
printf("1");
i = setjmp(ebuf);
if (i == 0)
{
fun();
printf("This will not be printed");
}
printf("%d\n", i);
return 0;
}
void fun(void)
{
printf("3");
longjmp(ebuf, 5);
}
//排序函数
#include
#include
int num[12] = {
14, 5, 9, 7, 6, 0, 91, 4, 1, 3, 2, 8
};
int comp(const void*, const void*);
int main()
{
int i;
printf("Oriqinal array:");//输出原数组
for (i = 0; i < 12; i++)
printf("%d", num[i]);
printf("\n");
qsort(num, 12, sizeof(int), comp);
printf("Sorted array:");//输出排序后数组
for (i = 0; i < 12; i++)
printf("%d", num[i]);
printf("\n");
return 0;
}
int comp(const void *i, const void *j)
{
return *(int*)i - *(int*)j;
}
//伪随机数生成
#include
#include
#include
int main()
{
long time1;
int i, time2;
time1 = time(NULL);
printf("%ld\n", time1);
time2 = (unsigned)time1 / 2;
printf("%ld\n", time2);
srand(time2);
for (i = 0; i < 10; i++)
printf("%d", rand());
printf("\n");
return 0;
}
//可变数目变元
/*
创建一个能获取可变数目变元的函数的通用过程:在函数定义中,可变参数表
之前必须有一个或多个已知参数,其中最右者为last_parm,在调用va_start时,
last_parm名被用作第二个参数
使用任何可变长度的变元被访问之前,必须先用va_start ()初始化argptr
必须调用va_end(),以确保堆栈的正确恢复
*/
//程序求0.5+0.25+0.125+0.06254之和
#include
#include
double sum_series(int num, ...);
int main()
{
double d;
//在子函数实际调用中共有五个参数,第一个为序列个数,其后为相加的各个数
d = sum_series(4, 0.5, 0.25, 0.125, 0.06254);
printf("sum of series is %f.\n", d);
return 0;
}
double sum_series(int num, ...)
{
double sum = 0.0, t;
va_list argptr;//定义参变量;
//初始化argptr
va_start(argptr, num);
//计算序列之和
for (; num; num--)
{
t = va_arg(argptr, double);
sum = sum + t;
}
//序列关闭
va_end(argptr);
return sum;
}
//链表
#include
#include
struct chain
{
int value;
struct chain* next;
};
struct chain *create()
{
struct chain* head, *tail, *p;
int x,i;
head = tail = NULL;
printf("请输入四个整形数据,然后回车:\n");
for (i = 0; i < 4; i++)
{
scanf("%d", &x);
p = (struct chain*)malloc(sizeof(struct chain));
p->value = x;
p->next = NULL;
if (head == NULL)
head = tail = p;
else
//tail倒数第二个表元指针
tail = tail->next;
tail->next = p;
}
return head;
}
struct chain* inlink(head,a,b)
struct chain* head;
int a, b;
{
struct chain*p, *q, *s;
s = (struct chain*)malloc(sizeof(struct chain));
s->value = b;
if (head == NULL)
{
head = s;
s->next = NULL;
}
if (head->value == a)
{
s->next = head;
}
else
{
p = head;
//遍历链表,寻找数据域值为a的节点
while ((p->value != a) && (p->next != NULL))
{
q = p;
p = p -> next;
}
if (p->value == a)
{
q->next = s;
s->next = p;
}
//插入节点s作为表尾
else
{
p->next = s;
s->next = NULL;
}
}
return (head);
}
struct chain* dellink(head, a)
struct chain* head;
int a;
{
struct chain*p, *q;
if (head == NULL)
printf("空链表\n");
else if (head->value == a)
{
p = head;
head = head->next;
}
else
{
p = head;
while ((p->value != a) && (p->next != NULL))
{
q = p;
p = p->next;
}
if (p->value != a)
printf("没有要删除的数据%d\n", a);
else
{
q->next = p->next;
free(p);
}
}
return (head);
}
void main()
{
struct chain*q, *head;
int a, b;
q = create();
head = q;
while (q)
{
printf("%d\n", q->value);
q = q->next;
}
printf("请输入新插入的表元数据位于那个数据之前:");
scanf("%d", &a);
printf("\n请输入要插入的表元数据:");
scanf("%d", &b);
q = inlink(head, a, b);
head = q;
while (q)
{
printf("%d\n", q->value);
q = q->next;
}
printf("请输入要删除的表元数据");
scanf("%d", &a);
q = dellink(head, a);
while (q)//显示链表
{
printf("%d\n", q->value);
q = q->next;
}
}
//队列的应用
#include
#define MAX 100
void SetNull(front, rear)
int *front, *rear;
{
*front = 0;
*rear = 0;
}
int Empty(front, rear)
int *front, *rear;
{
if (*front == *rear)
return(1);
else
return(0);
}
int EnQueue(q, x, front, rear)
int q[];
int x;
int *front, *rear;
{
*rear = (*rear + 1) % MAX;
if (*front == *rear)
{
printf("队列发生上溢\n");
return(-1);
}
else
{
q[*rear] = x;
return(0);
}
}
int DelQueue(q, y, front, rear)
int q[];
int *y;
int *front, *rear;
{
*front = (*front + 1) % MAX;
if (*front == *rear)
{
printf("队列发生下溢\n");
return(-1);
}
else
{
*y = q[*front];
return(0);
}
}
void main()
{
int q[MAX];
int f = 0,r = 0;
int i, m, x, n;
int a;
SetNull(&f, &r);
printf("要输入队列的字符个数:\n");
scanf("%d", &m);
printf("输入队列的整形数据:\n");
for (i = 0; i < m; i++)
{
i = i;
scanf("%d", &x);
a = EnQueue(q, x, &f, &r);
if (a == -1)
break;
}
printf("要提出队列的字符个数:");
scanf("%d", &n);
printf("输出从队列中提取的数据:\n");
for (i = 0; i < n; i++)
{
if (DelQueue(q, &x, &f, &r) == -1)
break;
printf("%d\n", x);
}
if (Empty(&f, &r) == 1)
printf("队列为空");
else
printf("队列中还有%d个数据", (m - n));
}
//堆栈的应用
#include
#include
#define MAX 100
int *p;
int *tos;
int *bos;
void push(int i)
{
if (p > bos)
{
printf("堆栈已满\n");
return;
}
*p = i;
p++;
}
int pop(void)
{
p--;
if (p < tos)
{
printf("堆栈下溢\n");
return 0;
}
return *p;
}
void main(void)
{
int a, b;
char s[80];
p = (int*)malloc(MAX*sizeof(int));
if (!p)
{
printf("分配内存失败");
exit(1);
}
tos = p;
bos = p + MAX - 1;
printf("请输入第一个数据:\n");
scanf("%d", &a);
push(a);
printf("请输入第二个数据:\n");
scanf("%d", &b);
push(b);
printf("请输入操作符:\n");
scanf("%s", s);
switch (*s)
{
case'+':
a = pop();
b = pop();
printf("结果是a+b=%d\n", (a + b));
push(a + b);
break;
case'-':
a = pop();
b = pop();
printf("结果是a-b=%d\n", (a - b));
push(a - b);
break;
case'*':
a = pop();
b = pop();
printf("结果是a*b=%d\n", (a * b));
push(a * b);
break;
case'/':
a = pop();
b = pop();
printf("结果是a/b=%d\n", (a / b));
push(a / b);
break;
default:
printf("请输入正确操作符\n");
}
}
//串的应用
#include
#include
#define MAX 100
typedef struct node
{
char Data[80];
struct node *Next;
}nodetype;
typedef struct head
{
int Num;
int Len;
nodetype* Next;
}headtype;
headtype Head[MAX];
void Inittial();//初始化各行头结点
int MenuSelect();//菜单选择函数
void EnterData();//输入数据函数
void DeleteLine();//整行删除数据
void List();//显示各行数据函数
void ClearBuffer();//清空缓存数据,与scanf配合使用
mian()
{
char choice;
Inittial();
while (1)
{
choice = MenuSelect();
switch (choice)
{
case 1:EnterData();
break;
case 2:DeleteLine();
break;
case 3:List();
break;
case 4:exit(0);
}
}
}
void Inittial()
{
int i;
for (i = 0; i < MAX; i++)
{
Head[i].Len = 0; //各行头结点长度参数置为零
}
}
int MenuSelect()
{
int i;
i = 0;
printf("1.Enter\n");
printf("2.Delete\n");
printf("3.List\n");
printf("4.Exit\n");
while (i <= 0 || i > 4)
{
printf("请输入菜单选择号\n");
scanf("%d", &i);
ClearBuffer();
}
return (i);
}
void EnterData()
{
nodetype *p, *find();
int i, j, m, Linenumber, k;
char StrBuffer[100];
while (1)
{
printf("输入数据要插入的行号(0-100):\n");
scanf("%d", &Linenumber);
ClearBuffer();
if (Linenumber < 0 || Linenumber >= MAX)
return;
printf("请输入要插入的数据,以@作为结束符号\n");
i = Linenumber;
Head[i].Num = Linenumber;
Head[i].Next = (nodetype*)malloc(sizeof(nodetype));
p = Head[i].Next;
m = 1;
j = -1;
StrBuffer[0] = 0;
k = 0;
do
{
j++;
if (!StrBuffer[k])
{
scanf("%s", StrBuffer);
k = 0;
}
if (j >= 80 * m)
{
m++;
p->Next = (nodetype*)malloc(sizeof(nodetype));
p = p->Next;
}
p->Data[j % 80] = StrBuffer[k++];
} while (p->Data[j % 80] != '@');
Head[i].Len = j;
}
}
void DeleteLine()
{
nodetype *p, *q;
int i, j, m, LineNumber;
while (1)
{
printf("输入要删除的行号(0-100):\n");
scanf("%d", &LineNumber);
if (LineNumber < 0 || LineNumber >= MAX)
return;
i = LineNumber;
p = Head[i].Next;
m = 0;
if (Head[i].Len>0)
{
m = (Head[i].Len - 1) / 80 + 1;
}
for (j = 0; j < m; j++)
{
q = p->Next;
free(p);
p = q;
}
Head[i].Len = 0;
Head[i].Num = 0;
}
}
void List()
{
nodetype *p;
int i, j, m, n;
for (i = 0; i < MAX; i++)
{
if (Head[i].Len>0)
{
printf("第%d行有数据.他们是:\n", Head[i].Num);
n = Head[i].Len;
m = 1;
p = Head[i].Next;
for (j = 0; j < n;j++)
if (j >= 80 * m)
{
p = p->Next;
m++;
}
else
printf("%c", p->Data[j % 80]);
printf("\n");
}
}
printf("\n");
}
//树的基本操作
#include
#include
struct tree
{
char info;
struct tree* left, *right;
};
struct tree* root;
struct tree *construct(struct tree *root, struct tree *r, char info);
void print(struct tree *r, int l);
int main(void)
{
char s[10];
root = NULL;
do
{
printf("请输入一个字符:");
gets(s);
root = construct(root, root, *s);
} while (*s);
printf(root, 0);
return 0;
}
struct tree *construct
(
struct tree *root,//新建树的根
struct tree *r,//新插入的节点
char info) //新插入节点的数据域
{
if (!r)
{
r = (struct tree*)malloc(sizeof (struct tree));
if (!r)
{
printf("内存分配失败");
exit(0);
}
//将该节点左右子树指针赋值为NULL,并使其数据域为参数info
r->left = NULL;
r->right = NULL;
r->info = info;
if (!root)
//如果root为NULL,则此插入值为该树的根
return r;
if (info < root->info)
//如果当前插入的节点比此子树的根小,则将这个节点作为此子树的右子树
root->left = r;
else
root->right = r;
}
//如果r为非空节点,则判断要插入的数据跟r数据域中的数据的大小,如果插入的数据比r节点数据域数据还小
if (info < r->info)
construct(r, r->left, info);
//则以r节点为新插入节点的根,将新数据作为左子树节点,递归调用construct函数
else
construct(r, r->right, info);
//否则r节点为新插入节点的根,将新数据作为右子树节点,递归调用construct函数
return root;
}
void print(struct tree* r, int l)
{
int i;
if (!r)
return;
print(r->left, l + 1);
for (i = 0; i < 1; i++)
printf(" ");
printf("%c\n", r->info);
print(r->right, l + 1);
}
//冒泡排序法
//冒泡排序法属于一种交换排序的类型,他从数组一端开始,以此对相邻两元素进行比较
//当发现他们不合顺序时就进行一次交换
#include
#include
bubble(strings, count) //冒泡排序函数
char *strings; //要排序的字符串
int count; //字符串的长度
{
register int m, n;
register char s;
for (m = 1; m < count;m++)
for (n = count - 1; n >= m; --n)
{
if (strings[n - 1]>strings[n])
{
s = strings[n - 1];
strings[n - 1] = strings[n];
strings[n] = s;
}
}
}
int main(void)
{
int count;
char str[200];
printf("请输入字符串:\n");
gets(str);
count = strlen(str);
bubble(str, count);
printf("排序后的字符串是:\n");
printf("%s.\n", str);
return 0;
}
//堆排序
#include
#define MARX 0
static a[11] = { MARX, 25, 4, 36, 1, 60, 10, 58, 14, 47, 18 };
int count = 1;
void heap(int n); //建立堆的函数
void adjust(int i, int n);
int main(void)
{
int i;
printf("源数据为:");
for (i = 1; i < 11; i++)
printf("%5d", a[i]);
heap(10);
printf("\n排序后的数据为:");
for (i = 1; i < 11; i++)
printf("%5d", a[i]);
printf("\n");
return 0;
}
void heap(n)
int n;
{
int i, j, t;
for (i = n / 2; i>0; i--)
adjust(i, n);
printf("\n初始化成堆===> ");
for (i = 1; i < 11; i++)
printf("%5d", a[i]);
for (i = n - 1; i>0; i--)
{
t = a[i + 1];
a[i + 1] = a[1];
a[1] == t;
printf("\n第2步操作结果===>", count++);
for (j = 1; j < 11; j++)
printf("%5d", a[j]);
}
}
void adjust(i, n)
int i, n;
{
int j, k, r;
int done = 0;
k = r = a[i];
j = 2 * i;
while ((j <= n) && (done == 0))
{
if (j < n)
{
if (a[j] < a[j + 1])
j++;
}
if (k >= a[j])
done = 1;
else
{
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j / 2] = r;
}
//归并排序
/*
二路归并排序定义:是把两个有序的序列合并成为一个有序的序列,
其排序的基本思想是将有n个记录的原始序列看作n个有序的子序列,
每个子序列的长度为1,然后从第一个子序列开始,把相邻的子序列两两
合并,得到(n/2)个长度为2或1的子序列,把这一过程称为一次归并排序.
*/
#include
void Mpass(int x[], int y[], int k, int n);
void Msort(int x[], int y[], int n);
int main(void)
{
int a[] = { 26, 5, 37, 1, 61, 11, 59, 14, 48, 19 };
int y[10];
int i;
printf("源数据为: ");
for (i = 0; i < 10; i++)
printf("[%2d]", a[i]);
Msort(a, y, 10);
printf("\n排序后的数据为: ");
for (i = 0; i < 10; i++)
printf("%4d", a[i]);
printf("\n");
return 0;
}
void Mpass(x, y, k, n)
int x[];
int y[];
int k;
int n;
{
int i, j;
int strat1, end1;
int strat2, end2;
int m;
strat1 = 0;
m = 0;
while (strat1 + k <= n - 1)
{
strat2 = strat1 + k;
end1 = strat2 - 1;
end2 = (strat2 + k - 1 <= n - 1) ? strat2 + k - 1 : n - 1;
for (i = strat1, j = strat2; i <= end1&&j <= end2;)
{
if (x[i] <= x[j])
{
y[m] = x[i];
i++;
m++;
}
else
{
y[m] = x[j];
j++;
m++;
}
}
while (i <= end1)
{
y[m] = x[i];
m++;
i++;
}
while (j <= end2)
{
y[m] = x[j];
m++;
j++;
}
strat1 = end2 + 1;
}
for (i = strat1; i < n; i++, m++)
y[m] = x[i];
}
void Msort(x, y, n)
int x[];
int y[];
int n;
{
int i, k, count;
k = 1;
count = 1;
while (k < n)
{
Mpass(x, y, k, n);
for (i = 0; i < n; i++)
x[i] = y[i];
printf("\n第%d步后的结果==> ", count++);
for (i = 1; i < n; i++)
{
if ((i == n) && (i % (2 * k) != 0))
printf("%4d", x[i - 1]);
else
{
if ((i % (2 * k)) == 1)
printf("%2d", x[i - 1]);
else if ((i % (2 * k)) == 0)
printf("%4d", x[i - 1]);
else
printf("%4d", x[i - 1]);
}
}
k = 2 * k;
}
}
//磁盘文件排序
#include
#include
#include
#define NUM 4
struct data
{
char name[20];
char school[20];
char city[20];
char province[20];
}info;
struct data addrs[NUM] =
{
"WenHai", "BIT", "JinLin", "JiLin",
"TongWei", "BIT", "ZhengJiang", "JiangSu",
"SunYou", "BIT", "WeiFang", "ShangDong",
"XiaoMing", "PKU", "TaiYuan", "ShanXi"
};
void quick_disk(FILE *fp, int count);
void qs_disk(FILE *fp, int left, int right);
void exchangedata(FILE *fp, long i, long j);
char *get_name(FILE* fp, long rec);
void print_data(struct data* p);
struct data *get_data(FILE *fp, long rec);
int main(void)
{
int i;
FILE* fp;
if ((fp = fopen("datalist.txt", "w+")) == NULL)
{
printf("打开文件夹\n");
exit(1);
}
printf("将没有排序的数据写入文件\n");
fwrite(addrs, sizeof(addrs), 1, fp);
for (i = 0; i < NUM; i++)
{
struct data* p;
p = get_data(fp, i);
print_data(p);
printf("\n");
}
fclose(fp);
if ((fp = fopen("datalist.txt", "rb+")) == NULL)
{
printf("不能以读写方式打开文件\n");
exit(1);
}
printf("将文件数据排序\n");
quick_disk(fp, NUM);
printf("排序结束\n");
for (i = 0; i < 4; i++)
{
struct data *p;
p = get_data(fp, i);
print_data(p);
printf("\n");
}
fclose(fp);
return 0;
}
void quick_disk(FILE *fp, int count)
{
qs_disk(fp, 0, count - 1);
}
void qs_disk(FILE *fp, int left, int right)
{
long int i, j;
char x[30];
i = left;
j = right;
strcpy(x, get_name(fp, (long)(i + j) / 2));
do
{
while ((strcmp(get_name(fp, i), x) < 0) && (i < right))
i++;
while ((strcmp(get_name(fp, j), x) > 0) && (j> left))
j--;
if (i <= j)
{
exchangedata(fp, i, j);
i++;
j--;
}
} while (i < j);
if (left < j)
qs_disk(fp, left, (int)j);
if (i < right)
qs_disk(fp, (int)i, right);
}
void exchangedata(FILE *fp, long i, long j)
{
char a[sizeof(info)], b[sizeof(info)];
fseek(fp, sizeof(info)*i, SEEK_SET);
fread(a, sizeof(info), 1, fp);
fseek(fp, sizeof(info)*j, SEEK_SET);
fwrite(b, sizeof(info), 1, fp);
fseek(fp, sizeof(info)*j, SEEK_SET);
fwrite(a, sizeof(info), 1, fp);
fseek(fp, sizeof(info)*i, SEEK_SET);
fwrite(b, sizeof(info), 1, fp);
}
char *get_name(FILE *fp, long rec)
{
struct data*p;
p = &info;
rewind(fp);
fseek(fp, rec*sizeof(struct data), SEEK_SET);
fread(p, sizeof(struct data), 1L, fp);
return p->name;
}
struct data* get_data(FILE *fp, long rec)
{
struct data *p;
p = &info;
rewind(fp);
fseek(fp, rec*sizeof(info), SEEK_SET);
fread(p, sizeof(info), 1, fp);
return p;
}
void print_data(struct data* p)
{
printf("姓名:%s\n", p->name);
printf("学校:%s\n", p->school);
printf("城市:%s\n", p->city);
printf("省:%s\n", p->province);
}
//顺序查找
#include
#include
#include
#define NUM 4
struct chain
{
char name[20];
char city[20];
char sex[10];
char age[10];
char job[10];
struct chain* next;
};
struct chain* create();
struct chain* SquelSeach(head, name);
void print_data(point);
struct chain Datas[NUM] =
{
"Sun", "Weifang", "Male", "24", "student", NULL,
"Tom", "Beijing", "Male", "31", "doctor", NULL,
"Marry", "Shanghai", "Female", "19", "techer", NULL,
"Willing", "Tianjing", "Female", "21", "worker", NULL,
};
int main(void)
{
struct chain* head;
struct chain* p;
char name[30];
head = create();
printf("请输入要查找的人名\n");
scanf("%s", name);
p = SquelSeach(head, name);
print_data(p);
return 0;
}
struct chain* create()
{
struct chain* head, *tail, *p;
int i;
head = tail = NULL;
printf("将名单数据输入到链表中:\n");
for (i = 0; i < NUM; i++)
{
p = (struct chain*)malloc(sizeof (struct chain));
strcpy(p->name, Datas[i].name);
strcpy(p->city, Datas[i].city);
strcpy(p->sex, Datas[i].sex);
strcpy(p->age, Datas[i].age);
strcpy(p->job, Datas[i].job);
p->next = NULL;
if (head == NULL)
head = tail = p;
else
{
tail = tail->next;
tail->next = p;
}
}
return head;
}
struct chain* SquelSeach(head,name)
struct chain* head;
char name[];
{
struct chain* temp;
temp = head;
for (temp = head; temp != NULL;)
{
if (strcmp(temp->name, name) == 0)
break;
else
temp = temp->next;
}
if (temp == NULL)
printf("没有查找到该人资料\n");
return temp;
}
void print_data(point)
struct Data* point;
{
if (point == NULL)
return;
printf("查找结果:\n");
printf(" 姓名:%s\n", point->name);
printf(" 城市:%s\n", point->city);
printf(" 性别:%s\n", point->sex);
printf(" 年龄:%s\n", point->age);
printf(" 工作:%s\n", point->job);
}
//树的动态查找
#include
#include
#include
#define NUM 4
struct tree
{
char name[20];
char city[20];
char sex[10];
char age[10];
char job[10];
struct tree* left;
struct tree* right;
};
struct tree Datas[NUM] =
{
"willing", "tianjing", "female", "21", "worker", NULL, NULL,
"tom", "beijing", "male", "31", "doctor", NULL, NULL,
"sun", "weifang", "male", "32", "student", NULL, NULL,
"marry", "shanghai", "female", "19", "techer", NULL, NULL
};
struct tree *constrcut(
struct tree *root,
struct tree* r,
struct tree *Data
)
{
if (!r)
{
r = (struct tree*)malloc(sizeof(struct tree));
if (!r)
{
printf("内存分配失败!");
exit(0);
}
r->left = NULL;
r->right = NULL;
strcpy(r->name, Data->name);
strcpy(r->city, Data->city);
strcpy(r->sex, Data->sex);
strcpy(r->age, Data->age);
strcpy(r->job, Data->job);
if (!root)
return r;
if (strcmp(Data->name, root->name) < 0)
root->left = r;
else
root->right = r;
return r;
}
if (strcmp(Data->name, r->name) < 0)
constrcut(r, r->left, Data);
else
constrcut(r, r->right, Data);
return root;
}
//查找关键字为name的节点
struct tree *Search(root,name)
struct tree* root;
char name[];
{
struct tree* p;
if (root == NULL)
printf("该树为空\n");
p = root;
while (strcmp(p->name, name) != 0)
{
if (strcmp(p->name, name) > 0)
p = p->left;
else
p = p->right;
if (p == NULL)
break;
}
return (p);
}
//中序遍历树的各个节点,并把各个节点的关键字name打印出来
void print(struct tree*r)
{
if (!r)
return;
print(r->left);
printf("%s\n", r->name);
print(r->right);
}
//打印指针point指向的节点
void print_currentData(struct tree* point)
{
if (point == NULL)
return;
printf(" 姓名:%s\n", point->name);
printf(" 城市:%s\n", point->city);
printf(" 性别:%s\n", point->sex);
printf(" 年龄:%s\n", point->age);
printf(" 工作:%s\n", point->job);
}
int main(void)
{
int i;
char c[10];
char swap[20];
char name[20];
struct tree* root, *p;
struct tree* temp;
p = NULL;
temp = NULL;
root = NULL;
for (i = 0; i < NUM:i++)
root = constrcut(root, root, &Datas[i]);
printf("现有人员资料:\n");
print(root);
printf("请输入要查找的人的名字\n");
scanf("%s", name);
p = Search(root, name);
if (p == NULL)
{
printf("没有该人资料\n");
printf("是否要插入该人资料[y/n]\n");
scanf("%s", c);
if (strcmp(c, "y") == 0)
{
temp = (struct tree*)malloc(sizeof(struct tree));
if (!temp)
{
printf("内存分配失败!");
exit(0);
}
printf("请输入该人姓名:\n");
scanf("%s", swap);
strcpy(temp->name, swap);
printf("请输入该人所在城市:\n");
scanf("%s", swap);
strcpy(temp->city, swap);
printf("请输入该人性别[Male/Female]:\n");
scanf("%s", swap);
strcpy(temp->sex, swap);
printf("请输入该人年龄:\n");
scanf("%s", swap);
strcpy(temp->age, swap);
printf("请输入该人工作:\n");
scanf("%s", swap);
strcpy(temp->job, swap);
temp->left = NULL;
temp->right = NULL;
root = constrcut(root, root, temp);
print_currentData(temp);
printf("现有人员资料: \n");
print(root);
}
else
return 0;
}
print_currentData(p);
return 1;
}
//二分法解方程
#include
#include
#include
#include
double Func(double);
int BisectRoot(double, double, double, double, double*, int, int*);
void main()
{
int i, n, m;
double a, b, h, eps, *x;
n = 3;
x = (double*)calloc(n, sizeof(double));// 开辟内存空间
if (x == NULL)
{
printf("内存分配失败\n");
exit(1);
}
a = -3; //区间起始端点
b = 7; //区间终止端点
h = 0.1; //扫描步长
eps = 1.e-8; //要求达到的精度
BisectRoot(a, b, h, eps, x, n, &m); //调用二分法函数
printf("y=sin(x)在范围%2.0f和%2.0f之间的根有%d个根\n", a, b, m);
printf("他们分别是: \n");
for (i = 0; i < n; i++)
printf("x=[%d]=%e\n", i, x[i]);
free(x);
}
double Func(double x)
{
return (sin(x));
}
int BisectRoot(a, b, h, eps, x, n, m)
double a;
double b;
double h;
double eps;
double *x;
int n;
int * m;
{
double z, z0, z1, y, y0, y1;
*m = 0;
z = a;
y = Func(z);
while (1)
{
if ((z > b + h/ 2) || (*m == n))
return (1);
if (fabs(y) < eps)
{
*m += 1;
x[*m - 1] = z;
z += h / 2;
y = Func(z);
continue;
}
z1 = z + h;
y1 = Func(z1);
if (fabs(y1) < eps)
{
*m += 1;
x[*m - 1] = z1;
z =z1+ h / 2;
y = Func(z);
continue;
}
if (y*y1>0)
{
y = y1;
z = z1;
continue;
}
while (1)
{
if (fabs(z1 - z) < eps)
{
*m += 1;
x[*m - 1] =(z1+ z)/2;
z = z1+h/ 2;
y = Func(z);
continue;
}
z0 = (z1 + z) / 2;
y0 = Func(z0);
if (fabs(y0) < eps)
{
*m =*m+ 1;
x[*m - 1] = z0;
z = z0 + h / 2;
y = Func(z);
break;
}
if (y*y0 < 0)
{
z1 = z0;
y1 = y0;
}
else
{
z = z0;
y = y0;
}
}
}
}
//牛顿迭代法求解方程
#include
#include
#include
int Function(double, double*, double* );
int Newton(double, double*, int);
void main()
{
double x, eps;
int l;
eps = 1.e-6;
x = 1.5;
l = 60;
if (!Newton(eps, &x, l))
//调用迭代函数,如果返回值为0,说明该方程不可以用迭代法
{
printf("该函数不可以用牛顿迭代法求根!\n");
}
printf("利用牛顿迭代法求解的根为:\n");
printf("x=%.10f\n", x);
}
int Function(x, f, dy)
double x;
double *f;
double *dy;
{
*f = x*x*(x - 1) - 1;
*dy = 3 * x*x - 2 * x;
return (1);
}
int Newton(x, eps, l)
double *x;
double eps;
int l;
{
double f, dy, xl;
Function(*x, &f, &dy);
A:if (fabs(dy) == 0)
//如果初值处函数一阶导数为零,则不可以用迭代法
{
l = 0;
return(0);
}
xl = *x - f / dy;
Function(xl, &f, &dy);
if (fabs(xl - *x) >= eps || fabs(f) >= eps)
{
l -= l;
*x = xl;
if (l == 0)
return (1);
goto A;
}
*x = xl;
return (1);
}
//弦截法求解方程
#include
#include
#include
#include
double Func(double);
int BowRoot(double, double, double, double, double*, int, int*);
void main()
{
int i, n, m;
double a, b, h, eps, *x;
n = 3;
x = (double*)calloc(n, sizeof(double));
if (x == NULL)
{
printf("内存分配失败\n");
exit(1);
}
a = -3;
b = 5;
h = 1;
eps = 1.e-8;
BowRoot(a, b, h, eps, x, n, &m);
printf("函数f(x)在范围%2.0f和%2.0f之间的根有%d个根\n", a, b, m);
printf("他们分别是:\n");
for (i = 0; i < n; i++)
printf("x[%d]=%e\n", i, x[i]);
free(x);
}
double Func(double x)
{
return (x*x*x - 3 * x*x - 6 * x + 8);
}
int BowRoot(a, b, h, eps, x, n, m)
double a; //实型变量,输入参数,求根区间的起始端点
double b; //实型变量,输入参数,求根区间的终止端点
double h; //利用逐步扫描法确定根位置时的步长
double eps; //实型变量,输入参数,存放计算得到的数组
double eps;//输入参数,区间内方程根的个数的预估值
double *x; //输入参数,实际求得的根的个数
int n;
int *m;
{
double z, z1, z2, y, y1, y2;
*m = 0;
*z = a;
y = Func(z);
while (1) //无限循环,直到遇到return或者break
{
if ((z > b + h / 2) || (*m == n))
return (1);
if (fabs(y) < eps)
{
*m += 1;
x[*m - 1] = z;
z += h / 2;
y = Func(z);
continue;
}
z1 = z + h;
y1 = Func(z1);
if (fabs(y1) < eps)
{
*m += 1;
x[*m - 1] == z1;
z = z1 + h / 2;
y = Func(z);
continue;
}
if (y*y1>0)
{
y = y1;
z = z1;
continue;
}
while (1)
{
if (fabs(z1 - z) < eps)
{
*m += 1;
x[*m - 1] = (z1 + z) / 2;
z = z1 + h / 2;
y = Func(z);
break;
}
y = Func(z1);
y = Func(z);
z2 = z1 - (y1 / (y1 - y)*(z1 - z));
y2 = Func(z2);
if (fabs(y2) < eps)
{
*m = *m + 1;
x[*m - 1] = z2;
z = z2 + h / 2;
y = Func(z);
break;
}
if (y*y2 < 0)
{
z1 = z2;
y1 = y2;
}
else
{
z = z2;
y = y2;
}
}
}
}
//拉格朗日插值
#include
#include
#include
double LAG(int, double*, double*, double);//拉格朗日插值函数
void main()
{
int n;
double *x, *y, t, lag;
t = 0.15;
n = 6;
x = (double*)calloc(n, sizeof(double));
if (x == NULL)
{
printf("内存分配失败\n");
exit(1);
}
y = (double*)calloc(n, sizeof(double));
if (y == NULL)
{
printf("内存分配失败\n");
exit(1);
}
x[0] = 0;
x[1] = 0.1;
x[2] = 0.195;
x[3] = 0.3;
x[4] = 0.401;
x[5] = 0.5;
y[0] = 0.39894;
y[1] = 0.39695;
y[2] = 0.39142;
y[3] = 0.38138;
y[4] = 0.36912;
y[5] = 0.35206;
lag = LAG(n, x, y, t);
printf("拉格朗日插值后得到的结果是:\n");
printf("f(%.2f)=%e\n", t, lag);
free(x);
free(y);
}
double LAG(n, x, y, t)
int n;
double *x;
double *y;
double t;
{
int i, j;
double p, s;
s = 0;
for (i = 0; i < n - 1; i++)
{
p = 1;
for (j = 0; j < n - 1;j++)
if (i != j)
p *= (t - x[j]) / (x[i] - x[j]);
s += p*y[i];
}
return (s);
}
//最小二乘法拟合
#include
#include
#include
#include
Smooth(double*, double*, double*, int, int, double*, double*, double*);
void main()
{
int i, n, m;
double* x, *y, *a, dt1, dt2, dt3, b;
n = 20;
m = 6;
b = 0;
x = (double*)calloc(n, sizeof(double));
if (x == NULL)
{
printf("内存分配失败\n");
exit(0);
}
y = (double*)calloc(n, sizeof(double));
if (y == NULL)
{
printf("内存分配失败\n");
exit(0);
}
a = (double*)calloc(n, sizeof(double));
if (a == NULL)
{
printf("内存分配失败\n");
exit(0);
}
for (i = 1; i <= n; i++)
{
x[i - 1] = b + (i - 1)*0.1;
//每隔0.1取个点连续取n个点
y[i - 1] = x[i - 1] - exp(-x[i - 1]);
//计算x[i-1]点对应的y值作为拟合已知值
}
Smooth(x, y, a, n, m, &dt1, &dt2, &dt3);
for (i = 1; i <= m; i++)
printf("a[%d]=%.10f\n", (i - 1), a[i - 1]);
printf("拟合多项式与数据点偏差的平方和为:\n");
printf("%.10e\n", dt1);
printf("拟合多项式与数据点偏差的绝对值之和为;\n");
printf("%.10e\n", dt2);
printf("拟合多项式与数据点偏差的绝对值最大值为:\n");
peintf("%.10e\n", dt3);
free(x);
free(y);
free(a);
}
Smooth(x, y, a, n, m, dt1, dt2, dt3)
double *x;
double *y;
double *a;
int n;
int m;
double *dt1;
double *dt2;
double *dt3;
{
int i, j, k;
double *s, *t, *b, z, d1, p, c, d2, g, q, dt;
s = (double*)calloc(n, sizeof(double));
if (s == NULL)
{
printf("内存分配失败\n");
exit(0);
}
t = (double*)calloc(n, sizeof(double));
if (t == NULL)
{
printf("内存分配失败\n");
exit(0);
}
b = (double*)calloc(n, sizeof(double));
if (b == = NULL)
{
printf("内存分配失败\n");
exit(0);
}
z = 0;
for (i = 1; i <= n; i++)
z = z + x[i - 1] / n;
b[0] = 1;
d1 = n;
p = 0;
c = 0;
for (i = 1; i <= n; i++)
{
p = p + x[i - 1] - z;
c = c + y[i - 1];
}
c = c / d1;
p = p / d1;
a[0] = c*b[0];
if (m > 1)
{
t[1] = 1;
t[0] = -p;
d2 = 0;
c = 0;
g = 0;
for (i = 1; i <= n; i++)
{
q = x[i - 1] - z - p;
d2 = d2 + q*q;
c = y[i - 1] * q + c;
q = (x[i - 1] - z)*q*q + g;
}
c = c / d2;
p = g / d2;
q = d2 / d1;
d1 = d2;
a[1] = c*t[1];
a[0] = c*t[0] + a[0];
}
for (j = 3; j <= m; j++)
{
s[j - 1] = t[j - 2];
s[j - 2] = -p*t[j - 2] + t[j - 3];
if (j>=4)
for (k = j - 2; k >= 2; k--)
s[k - 1] = -p*t[k - 1] + t[k - 2] - q*b[k - 1];
s[0] = -p*t[0] - q*b[0];
d2 = 0;
c = 0;
g = 0;
for (i = 1; i <= n; i++)
{
q = s[j - 1];
for (k = j - 1; k >= 1; k--)
q = q*(x[i - 1] - z) + s[k - 1];
d2 = d2 + q*q;
c = y[i - 1] * q + c;
g = (x[i - 1] - z)*q*q + g;
}
c = c / d2;
p = g / d2;
q = d2 / d1;
d1 = d2;
a[j - 1] = c*s[j - 1];
t[j - 1] = s[j - 1];
for (k = j - 1; k >= 1; k--)
{
a[k - 1] = c*s[k - 1] + a[k - 1];
b[k - 1] = t[k - 1];
t[k - 1] = s[k - 1];
}
}
*dt1 = 0;
*dt2 = 0;
*dt3 = 0;
for (i = 1; i <= n; i++)
{
q = a[m - 1];
for (k = m - 1; k >= 1; k--)
q = q*(x[i - 1] - z) + a[k - 1];
dt = q - y[i - 1];
if (fabs(dt) > *dt3)
*dt3 - fabs(dt);
*dt1 = *dt1 + dt*dt;
*dt2 = *dt2 + fabs(dt);
}
free(s);
free(t);
free(b);
return(1);
}
//辛普生数值积分
#include
#include
double Function(double);
double STMP1(double, double, int);
double STMP2(double, double, double);
void main()
{
double a1, b1, eps;
int n1;
double Result1;
double Result2;
a1 = 0.0;
b1 = 0.8;
n1 = 4;
eps = 5e-7;
Result1 = STMP1(a1, b1,n1);
Result2 = STMP2(a1, b1, eps);
printf("利用定步长辛普生积分结果为:\n");
printf("I1=%.10f\n", Result1);
printf("利用变步长辛普生积分结果为:\n");
printf("I2=%e\n", Result2);
}
double STMP1(a, b, n)
double a;
double b;
int n;
{
int i;
double h, s;
h = (a - b) / (2 * n);
s = 0.5*(Function(a) - Function(b));
for (i = 1; i <= n; i++)
s += 2 * Function(a + (2 * i - 1)*h) + Function(a + 2 * i*h);
return ((b - a)*s / (3 * n));
}
double STMP2(a, b, eps)
double a;
double b;
double eps;
{
int k, n;
double h, t1, t2, s1, s2, , p, x;
n = 1;
h = b - a;
t1 = h*(Function(a) + Function(b)) / 2;
s1 = t1;
while (1)
{
p = 0;
for (k = 0; k <= n; k++)
{
x = a + (k + 0.5)*h;
p += Function(x);
}
t2 = (t1 + h*p) / 2;
s2 = (4 * t2 - t1) / 3;
if (fabs(s2 - s1) >= eps)
{
t1 = t2;
n = n + n;
h = h / 2;
s1 = s2;
continue;
}
break;
}
return(s2);
}
double Function(double x)
{
return (cos(x));
}