欢度五一之C++编程练习

//2-54求三角形的面积(正弦定理)

float area_traingle(float a, float b, float c) {
	if (a + b > c && a + c > b && b + c > a) {
		float cosA = (b * b + c * c - a * a) / (2.0 * b * c);
		float sinA = sqrt(1 - cosA * cosA);
		float s = 0.5 * b * c * sinA;
		return s;
	}
	else {

		return 0;
	}
}

//2-55输入大写字母,转为小写字母输出

inline char letter_change(char x) {
	return x + 32;
}
//2-58找出二维数组(n阶方阵)每一行的最大元素
int array_max_row(const int *p,int rows_size) {
	int max = *p;
	for (int i = 0; i < rows_size; i++) {
		if(max < *p)
			max = *p;
		p++;
	}
	return max;
}

//2-59将输入的3个数降序排列

void sort_three_numbers(int* p1, int* p2, int* p3) {
	int arr[] = { *p1,*p2,*p3 };
	
	for(int i=0;i<3;i++)
		for (int j = 0; j < 2 - i; j++) {
			if (arr[j]<arr[j+1]) {
				int t = arr[j+1];
				arr[j+1] = arr[j];
				arr[j] = t;
			}

		}
	for (auto i : arr)
		std::cout << i << " ";
}

//2-60将一个数组中的元素顺序颠倒(双指针法)

void exchang_array_sort(int * arr , int size) {
	int i = 0, j = size - 1,temp=0;
	while (i <= j) {
		temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
		i++;
		j--;
	}
}

//求fibonacci数列的前n项(动态数组实现)

void fibo(int arr[], int n) {
	
	arr[0] = arr[1] = 1;
	std::cout << arr[0] <<" "<< arr[1] <<" ";
	for (int i = 2; i < n; i++) {
		arr[i] = arr[i - 1] + arr[i - 2];
		std::cout << arr[i] << " ";
	}
}

//2-61判断两个字符串是否相等

void string_compare(char str1[], char str2[]) {
	if (strcmp(str1, str2) == 0)
		std::cout << "Equal\n";
	else
		std::cout << "Unequal\n";
}

//2-62将输入的一个整数转换为字符串

string int_to_string(int num) {
	bool is_negtive = false;
	std::string str_num = "";
	if (num < 0) {
		num = -num;//转为正数
		is_negtive = true;
	}
	do
	{
		str_num = char(num % 10 + '0') + str_num;
		num /= 10;
	} while (num !=0);
	if (is_negtive) {
		str_num = "-" + str_num;
	}
	return str_num;
}

//2-63输入一行英文,将每个单词的首字母大写

void lower_to_upper(string& str) {
	
	for (int i = 0; i < str.size() - 1; i++) {

		if (isalpha(str[0]))
			str[0] = toupper(str[0]);
		if (ispunct(str[i]) || isspace(str[i]))
			str[i + 1] = toupper(str[i + 1]);
	}
	std::cout << str <<std:: endl;
}

//2-64 编写字符串比较函数 strcmp()对str1和str2 两个字符串进行比较返回值为int, str1str2 return 1; str1=str2 return 0;

int strcmp(string str1, string str2) {
	//确定循环次数
	int length = str1.size() > str2.size()? str1.size() :str2.size();

	for (int i = 0; i < length; i++) {
		if (str1[i] < str2[i])
			return -1;
		else if (str1[i] > str2[i])
			return 1;
	}
	return 0;
}

祝大佬们五一快乐!

你可能感兴趣的:(刷题系列,c++,算法,开发语言,数据结构)