c语言sqrt函数无作用,如何在不使用C语言的sqrt函数的情况下获得数字的平方根...
每個(gè)C程序員都知道C編程語(yǔ)言的math.h頭文件。該標(biāo)題定義了各種數(shù)學(xué)函數(shù)和一個(gè)宏。該庫(kù)中所有可用的函數(shù)都將double作為參數(shù), 并返回double作為結(jié)果。
該庫(kù)的已知功能之一是sqrt函數(shù), 這是非常有用的函數(shù)double sqrt(double number), 它返回?cái)?shù)字的平方根:
#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);
}
很容易吧?但是, 大學(xué)的老師不喜歡讓學(xué)生容易點(diǎn), 這就是為什么在編程課上你可能需要找到一種方法來(lái)找到數(shù)字的平方根而不使用C中的該庫(kù)!
由于作業(yè)或任務(wù)不是可選的, 因此我們將向你展示如何在不使用C語(yǔ)言的sqrt函數(shù)的情況下輕松實(shí)現(xiàn)這一目標(biāo)。
實(shí)現(xiàn)
首先, 我們將直接為你提供解決方案, 并在文章結(jié)尾進(jìn)行說(shuō)明:
#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);
}
代碼如下所示:最初, 程序?qū)⑻崾居脩?hù)輸入我們要從中查找平方根的數(shù)字。我們將數(shù)字的一半存儲(chǔ)在一個(gè)變量中, 將其除以2, 即sqrt。然后, 我們將聲明一個(gè)temp變量, 該變量將存儲(chǔ)sqrt先前值即temp的副本。最后, 我們將循環(huán)直到sqrt變量與temp不同為止, 在內(nèi)部, 我們將使用先前的sqrt值更新temp的值, 依此類(lèi)推。 sqrt值通過(guò)代碼中描述的操作更新, 僅此而已。循環(huán)結(jié)束后, 你將可以打印數(shù)字的平方根。
編碼愉快!
總結(jié)
以上是生活随笔為你收集整理的c语言sqrt函数无作用,如何在不使用C语言的sqrt函数的情况下获得数字的平方根...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 一些服务器编程的概念
- 下一篇: YUM仓库搭建