您的位置:首页 > 其它

指针的简单练习

2014-12-19 08:58 141 查看
1.给定一个整型数组,求该数组中数值小于 10 的元素的个数。

int counter(int* array, int length,int* countp)
{
int count=0;
if(array == NULL) return -1;
if(length <= 0) return -1;
if(countp == NULL) return -1;
for(int i=0;i<length;i++) count+=(array[i]<10)?1:0;
//printf(“the count of the number less than 10 is %d.\n”,count);//for debug
*countp = count;
return 0;
}

//2.给定一个整型数组,计算大于该数组平均值的元素的个数。

⁃ int counter(int* array, int length,int* countp)
{
int count=0, sum=0;
if(array == NULL) return -1;
if(length <= 0) return -1;
if(countp == NULL) return -1;
for(int j=0;j<length;j++) sum+=array[j];
for(int i=0;i<length;i++) count+=(array[i]>((double)sum/(double)length))?1:0;
//printf(“the count of the number greater than the average %lf is %d.\n”,(double)sum/(double)length,count);//for debug
*countp = count;
return 0;
}

//3.给定一个整型数组,找到数组中的最小值,并将其放到数组的首元素中,
原来首元素的内容放到最小值所在的元素中。

3.给定一个整型数组,找到数组中的最小值,并将其放到数组的首元素中,原来首元

素的内容放到最小值所在的元素中。
int exchange(int* array, int length)
{
int index=0, i=0,temp=0;

if(array == NULL) return -1;
if(length <= 0) return -1;

for(i=1;i<length;i++) index=(array[index]<array[i])?index:i;
temp=array[0];array[0]=array[index];array[index]=temp;
return 0;
}

//4.给定一个整型数组,统计某个整数在数组中出现的次数。

⁃ int counter(int* array, int length,int n,int* countp)
{
int count=0;
if(array == NULL) return -1;
if(length <= 0) return -1;
//if(n <= 0) return -1;//no proper illegal check
if(countp == NULL) return -1;

for(int i=0;i<10;i++) count+=(array[i]==n)?1:0;
//printf(“the count of the number %d is %d.\n”,n,count);//for debug
*countp = count;
return 0;
}

5.给定一个英文句子,单词之间用 1 个空格分开,求出第 n 个单词的偏移位置。例如

//“Professor du comes from Korea”的偏移位置是 10。

int location(char* s, int length,int n,int* location)
{
//char *s = “Professor du comes from Korea”;
char ch=‘\0’;
int index=0;

if(s == NULL) return -1;
if(length <= 0) return -1;
if(n <= 0) return -1;
if(location == NULL) return -1;

ch=s[0];
index=1;
while(ch!=‘\0’) {ch=s[index++]; if(ch == ‘ ’)break;}

//printf(“The index of the second word is %d.\n”,index);//for debug
*location = index;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: