- C语言Math库中有个函数sqrt可以直接调用
while ((scanf_s("%f", &number)) != EOF)
{
printf_s("%f", sqrt(number));
}
- 也可使用数学公式来算,即为计算近似值来求,当某个近似值与前一个近似值相等时,这个值就是平方根的值
设一个数列an,a1=1,a2=(a1+n/a1)/2…an=(an-1+n/an-1)/2
int main()
{
float an[500] = { 1.0 };//数列an
float number;
int i;
float t; //临时变量,存值
while ((scanf_s("%f", &number)) != EOF)
{
if (number < 0)
{
puts("Can not compute the number!");
return EXIT_FAILURE;
}
for (i = 1; i != 500; ++i)
{
t = an[i - 1] + number / an[i - 1];
an[i] = t / 2;
/*查看每次计算结果
printf_s("current result is %f\n", an[i]);*/
if (an[i] == an[i - 1])
{
printf_s("the square root of %f is %f\n", number,an[i]);
break;
}
}
}
return EXIT_SUCCESS;
}
考虑到空间使用,简约版
int main()
{
float current_result;
float last_result;
float number;
while ((scanf("%f",&number))!=EOF)
{
if (number<0)
{
puts("Can not compute the number!");
return EXIT_FAILURE;
}
current_result = 1.0f;
do
{
last_result = current_result;
current_result = (last_result + number / last_result) / 2;
printf_s("%f\n", current_result);
} while (current_result!=last_result);
/*%g为自动选择合适的输出格式*/
printf_s("the result is %g is %g\n", number, current_result);
}
return EXIT_SUCCESS;
}