C笔试给了几道小题,做一下.记录一下.用GCC编译测试通过,直接复制使用不报错
交换两个数:
#include<stdio.h>
int Swap(int* x,int* y)//形参
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
int main()
{
int a,b;
printf("Please enter two numbers:");
scanf("%d %d",&a,&b);
Swap(&a,&b);//实参
printf("a=%d b=%d\n",a,b);
return 0;
}
#include<stdio.h>
#include<assert.h>
char *my_strcpy(char *dst,char const *src)
{
char *ret=dst;//为了实现链式操作,将目的地址返回
assert(dst);
assert(src);//对源地址和目的地址加非空断言
if(dst==src)
return dst;//源目所指区域重叠,直接返回目的地址
while(*dst !='\0')
{
*dst=*src;
dst++;
src++;
}
/*可优化为:
while(*dst++=*src++)
{
NULL;
}*/
return ret;
}
int main()
{ char arr[]="you are the worst";
char *a="you are the best";
printf("%s\n",my_strcpy(arr,a));
getchar();
return 0;
}
#include<stdio.h>
int my_strlen(char const *str)
{
char const *tmp=str;
while(*str !='\0')
{
str++;
}
return str-tmp;
}
int main() {
char arr[30] = "trouble is a friend.";
printf("%d\n", my_strlen(arr));
getchar();
return 0;
}
对字串反序输出
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
scanf("%s",str);
int len;
len=strlen(str);
int fuction(char *, int);
fuction(str,len);
return 0;
}
解1:用下标
int fuction(char *s, int n)
{
int i;
for(i=n-1;i>=0;i--)
printf("%c",s[i]);
printf("\n");
return 1; //题目中并未提出对返回值的要求,随便输出1
}
解2:用指针
int fuction(char *s, int n)
{
char *p;
for(p=s+n-1;p>=s;p--)
printf("%c",*p);
printf("\n");
return 1; //题目中并未提出对返回值的要求,随便输出1
}
注意字符串中不要有空格。
#include <stdio.h>
#include <string.h>
void reverse(char s[])
{
int i, j, len = strlen(s);
char t;
for (i = 0, j = len - 1; i < len / 2; i++, j--)
{
t = s[i];
s[i] = s[j];
s[j] = t;
}
}
int main()
{
char s[50];
printf("input string:\n");
gets(s);
reverse(s);
printf("after reverse:\n");
puts(s); //注意:题目要求需在主函数中输入和输出字符串
return 0;
}
也是反序输出