C语言编程入门——函数调用解一元二次方程

【函数传值】
向函数传值是函数间传递数据的基本方式,简称传值方式。实质是调用函数把实参的值复制了一份传给了被调用函数的形参,使形参获得了初始值,无副作用。
【函数传址】
函数传址是函数间传递数据的又一种方式,简称传址方式。实质是调用函数把一个或多个内存地址传递给被调函数的形参,使形参指向了内存中的指定位置,有副作用。
以下例子运用了函数传值和传址的方式进行函数调用解出了一元二次方程:

//解一元二次方程ax^2+bx+c=0,练习函数调用,传值和传址的理解
#include<stdio.h>
#include<math.h>
//函数声明
void getdata (int *a,int*b, int *c);
 int quadratic(int a,int b,int c, double *proot1, double*proot2);
 void printresults(int numberroots, int a,int b,int c,double root1, double root2);
 //主程序
 int main()
 {
     int a,b,c,numberroots;
     double root1,root2;
     char again='Y';
     printf("solve quadratic equations \n\n");
     while(again=='Y'||again=='y')    /*可保证继续输入然后继续计算*/
     {
         getdata(&a,&b,&c);/*作用是输入三个变量的值,用函数传址的办法*/
         numberroots=quadratic(a,b,c,&root1,&root2);/*计算函数*/
         printresults(numberroots,a,b,c,root1,root2);/*输出函数*/
         getchar ();
         printf("\n do you have another equation (Y/N):");
         scanf("%c",&again);
     }
     printf("\n thank you.\n");
     return 0;
 }
 //getdata函数定义
 void getdata(int *pa,int *pb,int *pc)
 {
     printf("piease enter coefficiences a,b and c;");
    scanf("%d %d %d",pa,pb,pc);
    return;
 }
 //quadratic函数定义,主要求解过程
 int quadratic(int a, int b, int c, double *proot1, double *proot2)
 {
     int result;
     double discriminant;
     double root;
     if(a==0&&b==0)
     {result=-1;}
     else if(a==0)
     {*proot1=-c/(double)b;
     result=1;
     }
     else
     {
         discriminant=b*b-(4*a*c);
         if(discriminant>=0)
         {
             root=sqrt(discriminant);
             *proot1=(-b+root)/(2*a);
             *proot2=(-b-root)/(2*a);
             result=2;
         }
         else 
             result=0;
     }
     return result;/*返回解的个数*/
 }
 //printresult函数定义
 void printresults(int numberroots,int a,int b,int c, double root1, double root2)
 {
     printf ("your equation : %dx^2+%dx+%d\n",a,b,c);
     switch(numberroots)
     {
     case 2:printf("roots are :%6.3f %6.3f\n",root1,root2);
         break;
     case 1:printf("only one root :%6.3f\n",root1);
         break;
     case 0:printf("roots are imaginary.\n");
         break;
     default :printf("invalid cofficients\n");
         break;
     }
         return;
 }
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值