如何发明平方根代码?

马苏德·穆罕默迪(Masoud Mohammadi)

我想编写一个代码,使不使用pow()求平方根。
这是我尝试过的:

#include <stdio.h>
#include <stdlib.h>

int main(){
    int a,I,sum=0,cnt=0;
    printf("enter number");
    scanf("%d",&a);
    for(I=1;sum<a;I+=2){
        sum+=I;
        cnt++;
    }
    printf("answer is:%d",cnt);
    return 0;
}

对于像4,9,16,...这样的数字,它可以工作,但对于像10,17,21,..这样的数字,它不工作,结果超出了应有的水平。
问题是什么?

吊床

你可以试试这个

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a,I,cnt=0;
    int sum = 0;
    printf("enter number");
    scanf("%d",&a);
    for(I=1;sum<a;I+=2){
    sum+=I;
    cnt++;

    if(sum > a)     //add this if statement to decrement cnt by 1 when sum exceeds a.
        cnt--;

    }
   printf("answer is:%d",cnt);
}

输入:

21

输出:

4

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章