習題12(指標2)
1、編寫函式strlen:功能為求任意字串的長度,形參要求用指標變數。
程式設計實現:求任意字串長度。
#include <stdio.h>
char strlen(char *ch)
{
int i=0;
for(;*ch!='\0';ch++)
i++;
return i;
}
void main()
{
char ch[100];
printf("請輸入字串:");
gets(ch);
printf("字元長度為:%d",strlen(ch));
}
2、編寫函式scount:功能為統計一個字串在另一個字串中出現的次數。
程式設計實現:求一個字串在另一個字串中出現的次數。
#include <stdio.h>
#include <string.h>
char scount(char *x,char *y)
{
int count=0,i,j;
for(i=0;i<strlen(x);i++)
{
for(j=0;j<strlen(y);j++)
if(x[i+j]!=y[j])
{
break;
}
if(j==strlen(y) && j!='\0')
{
count++;
}
}
return count;
}
void main()
{
char m[100],n[100];
int i;
printf("請輸入字串:");
gets(m);
printf("請輸入要查詢的字元:");
gets(n);
i=scount(m,n);
if(i==-1)
printf("沒找到");
else
printf("%s在%s出現了%d次\n",n,m,i);
}
3、編寫函式divi:功能為求出任意正整數的所有不是偶數的因子並把它們按從小到大的順序存放在陣列中,要求函式返回陣列地址,且陣列最後一個元素為0。
程式設計實現:輸出任意正整數所有的不是偶數的因子。
#include<stdio.h>
void divi(int x, int *p, int *count)
{
int i,j = 0;
for(i=1;i<=x;i++)
{
if(x%i == 0&&i%2 != 0)
{
*(p + j) = i;
j++;
}
}
*count = j;
}
void main()
{
int i, p[100],count, x;
printf("請輸入整數:");
scanf("%d", &x);
divi(x, p, &count);
for(i=0;i<count;i++)
{
printf("%d ",*(p+i));
}
}
小胖專屬學習分享