//冒泡排序
#define N 10
int main() {
int i, j;
int a[N] = { 5,6,2,1,8,9,10,3,4,11 };
int temp;
for (i = N; i > 1; --i) {
for (j = 0; j < i-1; ++j) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (i = 0; i < N; ++i) {
printf("%d ", a[i]);
}
}
//选择排序
#define N 10
int main() {
int i, j,minpos;
int a[N] = { 5,6,2,1,8,9,10,3,4,11 };
int min;
for (i = 0; i <N; ++i) {
min = a[i];
minpos = i;
for (j = i+1 ; j < N; ++j) {
if (a[j] < a[minpos]) {
min = a[j];
minpos = j;
}
}
a[minpos] = a[i];
a[i] = min;
}
for (i = 0; i < N; ++i) {
printf("%d ", a[i]);
}
}
//矩阵法求定积分 下限a 上限b 分为n等分 p为函数指针 指向函数float 返回值为float型
//定积分函数
float count(float a, float b, int n,float (*p)(float)){
float sum = 0;
for (int i = 1; i <= n; ++i) {
sum += (*p)(a + (b - a) / n * i)*(b - a) / n; //(*p)(x)调用函数
}
return sum;
}
float fsin(float a) { //sin函数 也就是求出各分块的sin(a + (b - a) / n * i)
return sin(a);
}
float fcos(float a) {
return cos(a);
}
int main() {
int a = 0, b = 1;
int n = 200000;
printf("%f\n",count(a, b, n, fsin));
printf("%f\n", count(a, b, n, fcos));
}
//牛顿迭代法求根 a*x*x*x+b*x*x+c*x+d=0
int main() {
float a, b, c, d;
scanf("%f%f%f%f", &a, &b, &c, &d);
float num; //根
float x = 1.0; //求在x附近的根
float x1, f1,f2;
do {
x1 = x;
f1 = a * x1*x1*x1 + b * x1*x1 + c * x1 + d;
f2 = 3 * a*x*x + 2 * b*x + c;
x = x1 - f1 / f2;
} while (fabs(x-x1) >= 1e-5);
printf("%f", x);
}
//二分法 A,B两个点为根的一个边界,通过一直缩小根的边界,从而获取根的值。
/二分法求该方程的根:2X^3-4X^2+3X-6=0
double func(double x) {
return 2 * x*x*x - 4 * x*x + 3 * x - 6;
}
double root(double a,double b) { //在(a,b)范围内求根
double x;
x = (a + b) / 2;
if (func(x) == 0) {
printf("根为%f\n", x);
}
else {
while (fabs(func(x)) >= 1e-5) {
if (func(x)*func(a) > 0) {
a = x;
}
else {
b = x;
}
x = (a + b) / 2;
}
}
printf("根为%f\n", x);
return x;
}
int main() {
root(-10, 10);
}
弦截法是一种求方程根的基本方法,思路:任取两个数x1、x2,求得对应的函数值f(x1)、f(x2)。如果两函数值同号,则重新取数,直到这两个函数值异号为止。连接(x1,f(x1))与(x2,f(x2))这两点形成的直线与x轴相交于一点x,求得对应的f(x),判断其与f(x1)、f(x2)中的哪个值同号。如f(x)与f(x1)同号,则f(x)为新的f(x1)。将新的f(x1)与f(x2)连接,如此循环直到f(x)小于某个确定的精度为止。
//用弦截法求方程 f(x)=x * x*x +2 * x*x + 5 * x - 1=0 的根
double func(double x) {
return x * x*x +2 * x*x + 5 * x - 1;
}
double root(double x1, double x2) {
double k, b, x;
do {
k = (func(x1) - func(x2)) / (x1 - x2);
b = func(x1) - k * x1;
x = -b / k;
if (func(x)*func(x1) >= 0) {
x1 = x;
}
else {
x2 = x;
}
} while (fabs(func(x)) >= 1e-5);
return x;
}
int main() {
double x1, x2;
scanf("%lf%lf", &x1, &x2);
while (func(x1) * func(x2) >= 0) {
printf("INPUT:x1 x2\n");
scanf("%lf%lf", &x1, &x2);
}
double x = root(x1, x2);
printf("根为%lf\n", x);
}
//统计输入字符中的单词个数
int main() {
char str[999] = { 0 };
int cnt = 0;//单词个数
gets(str);
//puts(str);
int i = 0;
while (str[i]) {
if (str[i] != ' ') {
++cnt;
++i;
while (str[i]&&str[i] != ' ') { //找到空格
++i;
}
}
else {
++i;
}
}
printf("%d", cnt);
}