函数调用—sqrt函数

来源:互联网 发布:阿里云io优化 编辑:程序博客网 时间:2024/05/20 15:38

sqrt函数举例;


#include <stdio.h>


int sqrt_02(int question);


void main()
{
int question  = -49,answer;


if(question < 0)


{
printf("error:负数没有平方根!\n");
}


answer = sqrt_02(question);


if(question < 0)
printf("error:sqrt returns %d\n,answer");
else 
printf("The aquare root of %d is %d\n",question,answer);
}
int sqrt_02( int question )
{
int temp = question/2;
    while(1)                                  //循环永远不结束,其中应有跳出与语句,rentun语句直接将返回值返回给函数
{
if(temp * temp == question)
return temp;                //此处return为跳出,否则temp减1在进行循环。
else 
temp -=1;
}
}



/*程序可以从while这改为


  while(temp--)
  {
       if(temp * temp == question)
 return temp
  }
   return -1;          return -1  表示返回值为-1,系统将会自动报错。
 */

说明:

sqrt函数为开平方根函数,()以上程序全为自己练习编写,或许还存在漏洞,还望各位浏览的大佬帮以指出)

此程序也可以不用定义sqrt,sqrt函数包含在#include<math.c>的头文件中,若使用函数时可以加上头文件。

0 0
原创粉丝点击