用c语言求一个数的平方根

12345678136464646464646464646不行就大家都


#include <stdio.h>
#include <math.h>

int main() {
   double number, square;
   printf("请输入一个数:");
   scanf("%lf", &number);
   // 使用sqrt函数求平方根
   square = sqrt(number);
   printf("该数的平方根为:%lf\n", square);
   return 0;
}
  • 我觉得可以用穷举法。虽然有点笨,但有效。
    从整数零开始查找,一直找到i*i == n。

    img


    我仅会点儿python,就用python代码走一下“算法逻辑”😅
#!/sur/bin/nve python
# coding: utf-8


def mysqrt(n):
    
    for i in range(n):
    
        if i*i == n:
            return i


if __name__ == '__main__':
    while True:
        n = input('\n输入整数:').strip()
    
        if not n.isdigit():
            print(f"\n{'输入错误!':~^36}\n")
        else:
            n = int(n)
            break

    print(f"\n整数{n}的整数平方根是{mysqrt(n)}。")


供参考,自己写个求平方根的函数:

#include <stdio.h>
#include <math.h>
#define  Eps 1e-10
double mysqrt(double x)
{
    double x0 = x;
    while (fabs(x0 * x0 - x) > Eps)
        x0 = 0.5 * (x0 + x / x0);
    return x0;
}
int main()
{
    double x = 0.25;
    scanf("%lf", &x);
    printf("%.10f", mysqrt(x));
    return 0;
}

【相关推荐】



  • 帮你找了个相似的问题, 你可以看下: https://ask.csdn.net/questions/7705319
  • 除此之外, 这篇博客: C语言 缓存区溢出 3221225725中的 解决办法: 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:

    思路来源:

    https://blog.csdn.net/qq_48508278/article/details/120358623

    办法:数组定义在主函数外面 作为全局变量

    #include<bits/stdc++.h>
    #define num 10000
    #define cmp <
    using namespace std;
    
    long a[1500000]; // 一百五十万
    
    int main()
    {
    	srand(time(NULL));
    	clock_t start, end; 
    	double Total_time;
    	long length; 
    	
    	long l = 600000;
    	long b[10];
    	for(int i = 0;i<10;i++) 
    	{
    		b[i] = l;
    		l = l+100000;
    	}
    	
    
    	
    	for(l=0;l<10;l++)
    	{
    		start = clock();
    		
    		int k;
    		length = b[l];
    		
    		for(k = 0;k<length;k++)
    		{
    			a[k] = rand()%num;
    		}
    		
    		
    		int i, j, temp;
    		cout << "length = " << length <<  endl;
    		cout << "开始直接插入排序(for)  ";
    		for(i = 1; i < length; i++)
    		{
    			temp = a[i];
    			for(j = i-1; j >= 0; j--)
    			{
    				if(temp cmp a[j])
    					a[j + 1] = a[j];
    				else
    					break;
    			}
    			a[j + 1] = temp;
    		}
    		cout << "排序完成! ";
    		
    		
    		end = clock();
    		Total_time = (double)(end - start) / CLOCKS_PER_SEC;
    		cout << "用时 = " << Total_time << endl <<endl;
    		start = end;
    	}
    	
    	
    	system("pause"); 
    	return 0;
    }
    
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^