交换两个变量内容、函数调用实现判断一个数是不是素数

1、C语言实现两个变量中内容的交换,我们有多种实现方式:

(1)再重新定义一个变量(给计算机增加负担)

(2)用加法或减法实现(若数值比较大,易造成溢出)

(3)按位异或运算(不用重新开辟空间,不会造成溢出)

#include<stdio.h>
#include<windows.h>
#include<math.h>
#pragma warning(disable:4996)

void Swap(int *x, int *y)//形式参数(只在函数中有效):函数名括号中的变量,因为形式参数只有在函数被调用的过程中才实例化(分配内存单元)
{
	*x = (*x)^(*y);//按位异或,相同为0,不同为1
	*y = (*x)^(*y);
	*x = (*x)^(*y);
}
int main()
{
	int x, y;
	printf("Please input\n");
	scanf("%d %d", &x, &y);
	Swap(&x, &y);//实际参数(常量、变量、表达式、函数等)
	printf("Please output x=%d,y=%d\n", x, y);
	system("pause");
	return 0;
}

形参实例化之后其实相当于实参的一份临时拷贝

任何函数,只要进行传参,必产生临时变量

2、判断一个数是不是素数

(1)素数就是除过1和它本身再无其他约数,所以模上除过它和1的其它数等于零的话,就不是素数

(2)模上2到它的二分之一之间的数

(3)模上2到它之间的所有奇数(不包括2)

(4)该数开方,模上2到它的开方数之间的数(最优函数实现方法)


#include<stdio.h>
#include<windows.h>
#include<math.h>
#pragma warning(disable:4996)

void is_suShu(int *x)
{
	int top;
	top= sqrt((double)(*x));//给一个数开方
	int i = 2;
	for (; i <= top; i++)//减少循环次数
	{
		if ((*x) % i == 0)//不是素数
		{
			break;
		}

		else if (i >=top)//开方之内的数已经判断完毕,运行到此说明是素数
		{
			printf("is sushu\n");
		}
	}

}

int main()
{
	int x;
	printf("Please input:\n");
	scanf("%d", &x);
	is_suShu(&x);
	system("pause");
	return 0;
}



猜你喜欢

转载自blog.csdn.net/na_hanqiannan/article/details/79952032
今日推荐