天天看点

c语言中不使用库函数的情况下实现库函数的功能

一、求一个数的平方根(取整)

#include<stdio.h>
#include<assert.h>
int Mysqrt(int n)
{
	assert(n >= 0);
	int i;
	for (i = 0; i * i <= n; i++)
	{
	}
	return i - 1;
}
int main()
{
	printf("%d\n", Mysqrt(0));
	printf("%d\n", Mysqrt(9));
	printf("%d\n", Mysqrt(11));
	printf("%d\n", Mysqrt(10000));
	printf("%d\n", Mysqrt(-1));
}
           

调试结果如下:

c语言中不使用库函数的情况下实现库函数的功能

二、求字符串长度

int Mystrlen(const char* str)//求字符串长度
{
	int i;
	for (i = 0; str[i] != '\0'; i++)
	{

	}
	return i;
}
int main()
{
	char c[] = { "abcd\0" };
	printf("%d", Mystrlen(c));
}
           

三、字符串连结

void Mystrcat(char *des, const char *src)//将src的字符串连接到des后面
{
	assert(des != NULL && src != NULL);
	while (*des != '\0')
	{
		des++;
	}
	while (*des++ = *src++);
	/*while (*src != '\0')
	{
		*des = *src;
		src++;
		des++;
	}
	*des = '\0';
	*/
}
           

四、比较字符串大小

(若str1<str2 则返回-1,大于则返回1,相等则返回0)

#include<stdio.h>
#include<assert.h>

int Mystrcmp(const char* str1, const char* str2)
{
	assert(*str1 != NULL && *str2 != NULL);
	while (*str1 == *str2 && *str1 != '\0')
	{
		str1++;
		str2++;
	}
	if (*str1 < *str2)
	{
			return -1;
	}
	else if (*str1 > * str2)
	{
		return 1;
	}
	return 0;
}
int main()
{
	printf("%d\n", Mystrcmp("abc", "xyz"));
	printf("%d\n", Mystrcmp("xayc", "xyz"));
	printf("%d\n", Mystrcmp("xyz", "xab"));
	printf("%d\n", Mystrcmp("xyz", "xyz"));

}
           

调试结果为:

-1

-1

1

继续阅读