File tree 1 file changed +37
-1
lines changed
1 file changed +37
-1
lines changed Original file line number Diff line number Diff line change 1
- #
1
+ //正数n的平方根可以通过计算一系列近似值来获得,每个近似值都比前一个更加接近准确值。第一个近似值是1,接下来的近似值则通过下面的公式来获得。
2
+
3
+
4
+ //编写一个程序,读入一个值,计算并打印出它的平方根。如果你将所有的近似值都打印出来,你会发现这种方法获得准确结果的速度有多快。原则上,这种计算可以永远进行下去,它会不断产生更加精确的结果。但在实际中,由于浮点变量的精度限制,程序无法一直计算下去。当某个近似值与前一个近似值相等时,你就可以让程序停止继续计算了。
5
+
6
+ //必须使用浮点变量,而且程序应该对负值输入进行检查。
7
+
8
+
9
+ // 计算一个数的平方根。
10
+ #include <stdio.h>
11
+ #include <stdlib.h>
12
+
13
+ int main (){
14
+ float new_guess ;
15
+ float last_guess ;
16
+ float number ;
17
+
18
+ // 催促用户输入,读取数据并对它进行检查。
19
+ printf ("Enter a number: " );
20
+ scanf ("%f" , & number );
21
+ if ( number < 0 ){
22
+ printf ("Cannot compute the square root of a " "negative number! \n" );
23
+ return EXIT_FAILURE ;
24
+ }
25
+
26
+ // 计算平方根的近似值,直到它的值不再变化。
27
+ new_guess = 1 ;
28
+ do {
29
+ last_guess = new_guess ;
30
+ new_guess = ( last_guess + number / last_guess ) / 2 ;
31
+ printf ("%.15e\n" , new_guess );
32
+ } while ( new_guess != last_guess );
33
+
34
+ // 打印结果
35
+ printf ("Square root of %g is %g\n" , number , new_guess );
36
+ return EXIT_SUCCESS ;
37
+ }
You can’t perform that action at this time.
0 commit comments