页码 |
|
161 | 交换两个整形变量的值 |
168 | 计算字符串长度的函数的2个程序 |
169 | 字符串复制的3个程序 |
174、175 | 依次打印被调用时提供的所有命令行参数的2个程序 |
176 | 打印输出两维整型数组,每行的元素打印在一个行里 |
181 | 求出两个用数组表示的向量的和 |
185 | 用函数指针机制定义采用弦线法求函数根的函数 |
187 | 用矩形方法求函数的积分的2个程序 |
返回 总目录
void swap(int *p, int *q) {
int t = *p;
*p = *q;
*q = t;
}
double sum(double a[], int n) {
int i;
double s = 0.0;
for (i = 0; i < n; i++)
s += a[i];
return s;
}
程序1:
int strLength (const char *s) {
int n = 0;
while (*s != '\0') {
s++;
n++;
}
}
程序2:
int strLength (const char *s) {
char *p = s;
while (*p != '\0') p++;
return p - s;
}
程序1:
void strCopy (char *s, const char *t) {
while ((*s = *t) != '\0') {
s++;
t++;
}
}
程序2:
void strCopy (char *s, const char *t) {
while (*s = *t) {
s++;
t++;
}
}
程序3
void strCopy (char *s, const char *t) {
while (*s++ = *t++)
;
}
程序1:
#include <stdio.h>
int main (int argc, char *argv[]) {
int i;
for (i = 0; i < argc; i++)
printf("%s%c", argv[i],
i < argc-1 ? ' ' :'\n');
return 0;
}
程序2:
#include <stdio.h>
int main (int argc, char *argv[]) {
while(*agrv != NULL)
printf("%s ", *argv++);
putchar('\n');
return 0;
}
void prtMatrix (int *mp, int m, int n) {
int i, j;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++)
printf("%d ", *(mp + i * n + j));
putchar('\n');
}
}
例:求出两个用数组表示的向量的和
double *vadd(double a[], double b[], int n) {
double *p;
int i;
p = (double *)malloc(n * sizeof(double));
if (p == NULL) return NULL;
for (i = 0; i < n; i++)
p[i] = a[i] + b[i];
return p;
}
double cross(MFP fp, double x1, double x2) {
double y1 = fp(x1), y2 = fp(x2);
return (x1 * y2 - x2 * y1) / (y2 - y1);
}
double root(MFP fp, double x1, double x2) {
double x, y, y1 = fp(x1);
do {
x = cross(fp, x1, x2);
y = fp(x);
if (y * y1 > 0.0) {
y1 = y;
x1 = x;
}
else
x2 = x;
} while (y >= 1E-6 || y <= -1E-6);
return x;
}
程序1:
#define DIVN 30
double numInt(MFP fp, double a, double b) {
double res = 0.0, step = (b - a) / DIVN;
/* DIVN 是划分小区间的数目 */
int i;
for (i = 0; i < DIVN; i++)
res += fp(a + i * step)
* step;
return res;
}
程序2(改进程序,根据实际情况自动决定划分数):
double numInt(MFP fp, double a, double b) {
long i, divn = 10;
double step, dif, res0,
res = (fp(b) + fp(a)) * (b - a) / 2;
for (dif = 1.0; dif > 1E-6 || dif < -1E-6; divn
*= 2) {
res0 = res;
step = (b - a) / divn;
for (res = 0.0, i = 0; i
< divn; i++)
res += fp(a + i * step) * step;
dif = res - res0;
}
return res;
}