函数

练习
1、写一个函数判断一个数是否为素数

#include <math.h>
int is_prime(int n)
{
	int j = 0;
	for (j =2; j<= sqrt(n); j++)
	{
		if (n % j == 0)
			return 0;
	}
    return 1;

}
int main()
{
	int i = 0;
	for (i = 1; i<= 200; i++)
	{
		if (is_prime(i))
			printf("%d  ",i);
	}
	return 0;
}

}

2、判断是否为闰年

int is_leap_year(int y)
{
	if (( y%4==0 &&  y%100!=0 )||(y%400 ==0))
		return 1;
	else
		return 0;
}

int main()
{
	int year = 0;
	for (year = 1000; year <= 2000; year ++)
	{
		if (is_leap_year(year))
			printf("%d  ",year);
	}

	return 0;
}
int is_leap_year(int y)
{
	if (((y%4==0)&&(y%100!=0))||(y%400 == 0))
		return 1;
	else
		return 0;
}

int main()
{
	int year = 0;
	printf("input a year, i will tell you if it is a leap year:>");
	scanf("%d", &year);
	if (is_leap_year(year))
		printf("%d is a leap year\n",year);
	else
		printf("%d is not a leap year\n",year);
	
	return 0;
}

3、实现一个有序整型数组的二分查找

int bi_search(int arr[],int sz, int v)
{
	int left = 0;
	int right = sz-1;
	int inpoint = 0;
	if (v<arr[0] || v > arr[right])
		return -1;
	while (left <= right)
	{
		inpoint = (left + right)/2;
		if (v >arr[inpoint])
			left = inpoint +1;
		else if (v < arr[inpoint])
			right = inpoint -1;
		else 
			return inpoint;
	}

}

int main()
{
	int arr[]={1,2,3,4,5,6,7,8,9,10};
	int sz = sizeof(arr)/sizeof(arr[0]);
	int k = 0;
	int ret = 0;
	printf("input a integer:>");
	scanf("%d",&k);
	ret = bi_search(arr,sz, k);
	if (ret == -1)
		printf("there is no %d in arr[]\n",k);
	else
		printf("the number with subscript【%d】 in the array is %d\n",ret,k);
	return 0;
}

4、每调用一次函数,将num加1

void Fcount(int* p)
{
	(*p)++;
	//*p += 1;
	return *p;
}

int main()
{
	int num = 0;
	Fcount(&num);
	printf("num = %d\n",num);
	Fcount(&num);
	printf("num = %d\n",num);
	Fcount(&num);
	printf("num = %d\n",num);
	return 0;
}

# include <atdio. h>
void conat_func(const int* );
void main (void);
void main(void)
{
int x[10];
int y;
//Set up the integer array
for (y=0; y<10; y++)
x[y] = y;
//Call conat_func(), passing the x array by reference
conat_func(x);
}
//The const_function receives an integer array by reference.
//Notice that the pointer i» declared aa const, which renders
//it unmodif table by the conat_funcO function
void conat_func(conat int* i)
{
int y;
//print the contents of the integer array
for (y=0; y<10; y++)
printf("%d\n", *(i+y));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值