1.折半查找
#include<stdio.h>
#include<windows.h>
#pragma warning (disable:4996)
//折半查找
int find(int x){
int arr[] = { 10, 20, 30, 40, 50, 60, 61, 65, 450, 470 };
int num = 0;
int left = 0;
int right = sizeof(arr) / sizeof(arr[0]);
while (left <= right){
num = (left + right) / 2;
if (x > arr[num]){
left = num + 1;
}
else if (x < arr[num]){
right = num - 1;
}
else{
return num ;
}
}
return -1;
}
int main(){
int n=0;
printf("请输入要查找的数:");
scanf("%d", &n);
printf("此数是是数组中第%d个数\n", find(n));
system("pause");
return 0;
2.1 计算 n的阶乘
#include<stdio.h>
#include<windows.h>
#pragma warning (disable:4996)
//阶乘计算
int Factorial(int x){
int index = 1;
while(x>0){
index *= x;
x--;
}
return index;
}
int main(){
int n=0;
printf("请输出要计算的阶乘数:");
scanf("%d", &n);
printf("%d的阶乘为%d\n",n,Factorial(n));
system("pause");
return 0;
}
2.2 计算 1!+2!+3!+……+10!
#include<stdio.h>
#include<windows.h>
#pragma warning (disable:4996)
//阶乘计算
int Factorial(int x){
int index = 1;
while(x>0){
index *= x;
x--;
}
return index;
}
int main(){
int n=0;
int num = 0;
int result = 0;
for (int i = 0; i < 11; i++){
num=Factorial(i);
result += num;
}
printf("1!+2!+3!+……+10!的阶乘为%d\n",result);
system("pause");
return 0;
}
3.多个字符从两端移动,向中间汇聚
#include<stdio.h>
#include<windows.h>
#pragma warning (disable:4996)
char arr1[] = "hello world" ;
char arr2[] = "###########" ;
int start = 0;
int end = strlen(arr1)-1;
for ( start = 0, end = strlen(arr1)-1;start<=end;start++,end--){
arr2[start] = arr1[start];
arr2[end] = arr1[end];
Sleep(1000);
printf("%s\n", arr2);
}
system("pause");
return 0;
}
4.打印100~200之间的素数
#include<stdio.h>
#include<windows.h>
int main(){
for (int i = 100; i < 201; i++){
int a = 1;
for (int j = 2; j < i; j++){
if (i%j == 0){
a = 0;
break;
}
}
if (a != 0){
printf("%d\n", i);
}
}
system("pause");
return 0;
}
5.给定两个数,求这两个数的最大公约数
#include<stdio.h>
#include<windows.h>
#pragma warning (disable:4996)
int Gdc(int x, int y){
int temp = 0;
while (y != 0){
temp = x%y;
x = y;
y = temp;
}
return x;
}
int main(){
int x = 0;
int y = 0;
int temp = 0;
printf("请输入<x,y>:");
scanf("%d %d", &x, &y);
if (x < y){
temp = y;
y = x;
x = temp;
}
printf("%d\n",Gdc(x, y));
system("pause");
return 0;
}
方法2 递归:
#include<stdio.h>
#include<windows.h>
#pragma warning(disable:4996)
int Gdc(int x, int y){
if (x%y == 0){
return y;
}
else
return Gdc(y, x%y);
}
int main(){
int x = 0;
int y = 0;
int temp = 0;
printf("请输入<x,y>:");
scanf("%d %d", &x, &y);
if (x < y){
temp = y;
y = x;
x = temp;
}
printf("%d\n", Gdc(x, y));
system("pause");
return 0;
6.求两个数的最小公倍数
#include<stdio.h>
#include<windows.h>
#pragma warning (disable:4996)
int Gdc(int x, int y){
int temp = 0;
while (y != 0){
temp = x%y;
x = y;
y = temp;
}
return x;
}
int MinComMultiple(int x, int y){
return x*y / Gdc(x, y);
}
int main(){
int x = 0;
int y = 0;
int temp = 0;
printf("请输入<x,y>:");
scanf("%d %d", &x, &y);
if (x < y){
temp = y;
y = x;
x = temp;
}
printf("%d\n", MinComMultiple(x,y));
system("pause");
return 0;
}