计算平方根

  • 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值