练习

1.计算n的阶乘

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int main(){
while (1)
{
int a, i;
int sum = 1;
scanf("%d", &a);
for (i = a; i >= 1; --i)
{
sum *= i;
}
printf("阶乘结果为:%d\n", sum);
}
return 0;
}

2.计算1!+2!+3!+......+10!

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int main(){
int i,a;
int sum;
int all = 0;
for (a = 10; a >= 1;--a)
{
sum = 1;
for (i = a; i >= 1; --i)
{
sum *= i;
}
all += sum;
}
printf("10!+9!+8!+7!+......+1!=%d\n", all);
return 0;
}

3.在有序序列中查找一个元素

(一)正常循环遍历
(二)折半查找法
具体代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int mid(int a, int b){
return (a + b) / 2;
}
int main(){
int a[] = {1,2,3,4,5,6,7,8,9,10};
int want;
int i;
int left = 0;
int right = 9;
printf("Please write down a number which you wanna find:");
scanf("%d", &want);
for (i = 0; i < 10; ++i)
{
if (a[mid(left, right)] == want){
printf("here:%d\n", a[mid(left, right)]);
break;
}
else if (a[mid(left, right)] < want){
left = mid(left, right) + 1;
}
else{
right = mid(left, right) - 1;
}
}
return 0;
}

4.将字符串依次首位各一个字符输出

Sleep()函数

Sleep(1000);//休息一秒
需要头文件#include <windows.h>
system("cls"); //清空屏幕
需要#include <stdlib.h>
可以加进代码中实现轮换播放
具体代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
int main(){
char ch[] = "welcome to qqhe";
char ch1[] = "###############";
int size = (sizeof(ch)) / (sizeof(ch[0])) - 2;//char[15]为'\0'
int left = 0;
int right = size - 1;
int i, j;
printf("%s\n", ch1);
for (i = 0, j = size; i <= j; ++i, --j){
ch1[i] = ch[i];
ch1[j] = ch[j];
printf("%s\n", ch1);
Sleep(1000);
system("cls");
}
return 0;
}