c语言sqrt函数无作用,如何在不使用C语言的sqrt函数的情况下获得数字的平方根...
每個C程序員都知道C編程語言的math.h頭文件。該標題定義了各種數學函數和一個宏。該庫中所有可用的函數都將double作為參數, 并返回double作為結果。
該庫的已知功能之一是sqrt函數, 這是非常有用的函數double sqrt(double number), 它返回數字的平方根:
#include
#include
int main () {
/// 2.000000
printf("Square root of %lf is %lf\n", 4.0, sqrt(4.0) );
/// 2.236068
printf("Square root of %lf is %lf\n", 5.0, sqrt(5.0) );
return(0);
}
很容易吧?但是, 大學的老師不喜歡讓學生容易點, 這就是為什么在編程課上你可能需要找到一種方法來找到數字的平方根而不使用C中的該庫!
由于作業或任務不是可選的, 因此我們將向你展示如何在不使用C語言的sqrt函數的情況下輕松實現這一目標。
實現
首先, 我們將直接為你提供解決方案, 并在文章結尾進行說明:
#include
void main()
{
int number;
float temp, sqrt;
printf("Provide the number: \n");
scanf("%d", &number);
// store the half of the given number e.g from 256 => 128
sqrt = number / 2;
temp = 0;
// Iterate until sqrt is different of temp, that is updated on the loop
while(sqrt != temp){
// initially 0, is updated with the initial value of 128
// (on second iteration = 65)
// and so on
temp = sqrt;
// Then, replace values (256 / 128 + 128 ) / 2 = 65
// (on second iteration 34.46923076923077)
// and so on
sqrt = ( number/temp + temp) / 2;
}
printf("The square root of '%d' is '%f'", number, sqrt);
}
代碼如下所示:最初, 程序將提示用戶輸入我們要從中查找平方根的數字。我們將數字的一半存儲在一個變量中, 將其除以2, 即sqrt。然后, 我們將聲明一個temp變量, 該變量將存儲sqrt先前值即temp的副本。最后, 我們將循環直到sqrt變量與temp不同為止, 在內部, 我們將使用先前的sqrt值更新temp的值, 依此類推。 sqrt值通過代碼中描述的操作更新, 僅此而已。循環結束后, 你將可以打印數字的平方根。
編碼愉快!
總結
以上是生活随笔為你收集整理的c语言sqrt函数无作用,如何在不使用C语言的sqrt函数的情况下获得数字的平方根...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一些服务器编程的概念
- 下一篇: YUM仓库搭建