[ACM]简单开方

Time Limit: 1000MS Memory Limit: 65536KB
Total Submissions: 15 Accepted: 8

Description:

Badming看看上周的题目,觉得太难了,就想把题目出简单一些。
求一个整数的开方√x。比如求 √99 =9 √100=10
但这样也太简单了吧,为了增加些许难度,x的范围是0-10^26

Input:

给定一个自然数x.
当x=0表示输入结束,不用再处理.

Output:

输出它的开方.

Sample Input:

16
26
35
0

Sample Output:

4
5
5

Hint:

Source:

DUT badming

 

解题思路:

这题算比较简单的题了,数值分析中的牛顿铁代就可以,当然也可以采用手动开发的思路。这里使用的是牛顿铁代的方法。当前后两个结果差值小于0.1时停止迭代。

 

代码如下:

  1: #include <stdio.h>
  2: #include <string.h>
  3: #include <math.h>
  4: 
  5: int main()
  6: {
  7: 	int digits;
  8: 	double n, x, pre;
  9: 	char chx[28];
 10: 
 11: 	while (scanf("%s", chx), chx[0] != '0')
 12: 	{
 13: 		n = atof(chx);
 14: 		digits = strlen(chx);
 15: 		x = pow(10.0, (digits - 1) / 2);
 16: 		pre = 0.0;
 17: 		while (fabs(pre - x) > 0.1)
 18: 		{
 19: 			pre = x;
 20: 			x = 0.5 * (x + n / x);
 21: 		}
 22: 		printf("%.0f
", floor(x));
 23: 	}
 24: 	return 0;
 25: }
 26: 

posted on 2010-04-03 13:09  小橋流水  阅读(253)  评论(0编辑  收藏  举报

导航