7.编写下列函数:
- bool search(const int a[], int n, int key);
a是待搜索的数组,n是数组中元素的数量,key是搜索键。如果key与数组a的某个元素匹配了,那么search函数返回true;否则返回false。要求使用指针算术运算而不是取下标来访问数组元素。
bool search(const int a[], int n, int key){
int *p, flag = 1;
for(p = a; p < a + n; p++)
{
if(*p == key)
{
flag = 0;
return true;
}
}
if(flag)
{
return false;
}
}
9.编写下列函数:
- double inner_product(const double *a, const double *b,
- int n);
a和b都指向长度为n的数组。函数返回a[0]*b[0]+a[1]*b[1]+...+a[n-1]*b[n-1]。要求使用指针算术运算而不是取下标来访问数组元素。
#include<stdio.h>
#include<stdlib.h>
double inner_product(const double *a, const double *b);
int main(void)
{
double a[3], b[3], t;
int i;
for(i = 0; i < 3; i++)
{
scanf("%lf", &a[i]);
}
for(i = 0; i < 3; i++)
{
scanf("%lf", &b[i]);
}
t = inner_product(a, b);
printf("%lf\n", t);
return 0;
}
double inner_product(const double *a, const double *b)
{
double const *p = NULL; //指针前面也要加上const,要不然会出系统可能会修改数组内容 的warnning。
double const *q = NULL;double sum;
for(p = a, q = b; p < a + 3 && q < b + 3; p++, q++) //for循环的第二个条件不能出现,因为编译无法识别逗号是什么 运算符,因此会出现left hand operand of comma expression has no effect 的警告所以要用&&来避免。
{
sum += (*p) * (*q);
}
return sum;
}
假设按如下方式调用scanf函数,scanf(“%d%s%d”, &i, s, &j);那么调用后i, s, j 的值是多少?
#include<stdio.h>
#include<string.h>
int main(void)
{
int i, j;
char s[100];
scanf("%d%s%d", &i, s, &j); //这里虽然没有空格但是 在进行编译的时候, 输入数据也要加上空格。否则无法进行编译。
printf("%d %s %d\n", i, s, j);
return 0;
}