1. 程式人生 > >小練習:陣列元素的交換

小練習:陣列元素的交換

/// 1.交換兩個陣列的元素,兩個陣列元素個數相同
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
	int arr1[] = { 2, 3, 5, 4, 6, 7, 9, 12, 34, 45 };
	int arr2[] = { 1, 9, 8, 0, 4, 6, 34, 56, 7, 23 };
	int i = 0, temp = 0;
	int size = sizeof(arr1) / sizeof(*arr1);//求陣列元素的個數
	printf("交換前:\n");
	printf("arr1陣列元素為:");
	for (i = 0; i < size; i++)
	{
		printf("%4d", arr1[i]);
	}
	printf("\n");
	printf("arr2陣列元素為:");
	for (i = 0; i < size; i++)
	{
		printf("%4d", arr2[i]);
	}
	printf("\n");

	for (i = 0; i < size; i++)
	{
		temp = arr1[i];
		arr1[i] = arr2[i];
		arr2[i] = temp;
	}
	printf("交換後:\n");

	printf("arr1陣列元素為:");
	for (i = 0; i < size; i++)
	{
		printf("%4d", arr1[i]);
	}
	printf("\n");
	printf("arr2陣列元素為:");
	for (i = 0; i < size; i++)
	{
		printf("%4d", arr2[i]);
	}
	fflush(stdin);
	getchar();
	return 0;
}



//2.求1/1 - 1/2 + 1/3 - 1/4......-1/100
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
	int i = 0;
	int flag = 1;
	double sum = 0;
	for (i = 1; i <= 100; i++)
	{
		sum = sum + (1.0 / i)*flag;//(1.0/i)表示強制轉換為浮點型
		flag = -flag;//實現加減交替
		//sum=sum+pow((-1),(1+i))*(1.0/i);//pow(a,b)為a的b次方,需要呼叫math.h
	}
	printf("求得結果為%lf", sum);
	getchar();
	return 0;
}



//3.求1到100裡面9出現的次數
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
	int i = 0, sum = 0;
	for (i = 1; i <= 100; i++)
	{
		if (i / 10 == 9)//十位上的9
		{
			sum++;
		}
		if (i % 10 == 9)//個位上的9
		{
			sum++;
		}
	}
	printf("1到100之間9總共出現了%d次", sum);
	getchar();
	return 0;
}