前置++和后置++,都是自增1,但是表达式返回值不同。执行效率上前置++更快。
前置++返回是自增之后的值。
等价于num+=1;
rerurn num;
后置++返回的是自增之前的值。
等价于 int tmp = num;
num +=1;
return tmp;
1.计算任意一阶的阶乘。
#include<stdio.h>
#include<stdlib.h>
int factor (int n)
{
int i = 1;
int ret = 1;
for(i=1;i<=n;i++)
{
ret *= i;
}
return ret;
}
int main()
{
printf("%d\n",factor(5));
system("pause");
return 0;
}
2.计算1!+2!+...+10!
#include<stdio.h>
#include<stdlib.h>
int i = 1;
int factor (int n)
{
int i = 1;
int ret = 1;
for(i=1;i<=n;i++)
{
ret *= i;
}
return ret;
}
int main()
{
int sum = 0;
for (i=1;i <= 10;++i)
{
sum +=factor(i);
}
printf("%d\n",sum);
system("pause");
return 0;
}
字符数组可以表示字符串变量。
例如char[100]="aaa"中,字符数组长度是100,字符串长度是3.
C语言中比较字符串是否相同,要使用strcmp()函数。
例如下面编写一个常用登陆操作过程。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i=0;
for(;i<3;++i){
char password[20] = "";
printf("请输入密码: ");
scanf("%s",password);
if(strcmp(password,"abcdef") == 0){
printf("登陆成功\n");
break;
}else {
printf("密码错误\n");
}
}
if(i==3){
printf("禁止登陆\n");
}
system("pause");
return 0;
}
查找一个数组中的元素。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int arr[5] = {5,10,2,7};
int to_find = 5;
int i =0;
for(;i<5;i++){
if(arr[i] == to_find){
break;
}
}
if(i == 5){
printf("没找到\n");
}else{
printf("找到了\n");
}
system("pause");
}
二分查找,前提是有序数组。
例如:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int arr [10] = {0,1,2,3,4,5,6,7,8,9};
int to_find = 8;
//取中间元素和要查找元素进行比较
//[left,right]待查找区间
int left = 0;
int right = 9;
while(left <= right){
//这个循环条件表示待查找区间中有元素需要查找
//mid 是中间位置元素的下标
int mid = (left + right)/2;
if(to_find < arr[mid]){
//mid 位置的元素已经比较过,不必再去继续比较
right = mid - 1;
}else if(to_find > arr[mid]){
left = mid +1;
}else {
//找到了
printf("找到了\n");
break;
}
}
if(left < = right){
printf("找到了\n");
}else{
printf("没找到\n");
system("pause");
return 0;
}