C语言程序设计 现代方法(第二版)第十二章练习题

12-7、编写下列函数
Bool search(int a[],int n,int key);
a是待搜索的数组,n是数组中的元素数量,key是搜索键。如果key与数组a中的某个元素匹配,则search返回true,否则返回false。不用数组下标访问数组,以指针算数运算替代。

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define N 50
bool search(int *a,int n,int key);
int main()
{
   int a[N]={0};
   int n;
   int key;
   int *input_point;
   input_point=a;
   printf("Please enter input number of:");
   scanf("%d",&n);
   printf("Enter of number array:");
   for(input_point=a;input_point<a+n;input_point++)
    {
        scanf("%d",&(*input_point));
    }
    printf("Enter of key:");
    scanf("%d",&key);
    if(search(a,n,key))//执行判断语句,如果返回值为真,则执行以下打印语句
    {
        printf("This key is true\n");
    }
    else printf("This key is false\n");
   return 0;
}
bool search(int *a,int n,int key)
{
    int *search_point;
    search_point=a;
    bool ret=false;
    for(search_point=a;search_point<a+n;search_point++)//p指针从指向数组a第一位开始遍历,直到数组第n位位置,每次自增整形数组一个字符。
    {
        if(*p==key)ret=true;
    }
    return ret;
}

12.8、用指针运算符修改以下函数
Void store_zeros(int a[],int n)
{
Int i;
for(i=0;i<n;i++)
a[i]=0;
}
修改后的函数为:

#include <stdio.h>
#include <stdlib.h>
#define N 10
void store_zeros(int *point,int n);
int main()
{
    int a[N]={1,2,3,4,5,6,7,8,9,10};
    int n = 10;
    store_zeros(a,n);
    int *print_point;
    print_point = a;
    for(print_point=a;print_point<a+n;print_point++)
        printf("%2d ",*print_point);
    return 0;
}
void store_zeros(int *a,int n)
{
    int *input_point;
    input_point = a;
    for(input_point=a;input_point<a+n;input_point++)
        *input_point =0;
}

12.9、用指针运算实现double inner_product(double *a,double b,int n),并且a、*b都指向长度为n的数组,进行a[0]*b[0]+…+a[n]*b[n]。

#include <stdio.h>
#include <stdlib.h>
#define N 10
double basic[N];//定义basic数组为全局变量,每个函数都可以调用修改保存。
void generate();
double count(double *a,double *b,int n);
int main()
{
    double sum;
    generate();
    sum=count(basic,basic,N);//传递数组basic
    printf("ret=%f\n",sum);
    return 0;
}
void generate()//此函数为生成数组,并对
  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值