我对编程非常陌生并且在尝试使用Heron公式创建程序时遇到问题,计算了数字的平方根的5个近似值 i < = 10.
公式为:
X n + 1 =( X n +( i / X n ))/ 2
我提出了以下代码,但它没有工作,因为输出什么都没有。
SCRIPT_NAME=/status SCRIPT_FILENAME=/status REQUEST_METHOD=GET cgi-fcgi -bind -connect /var/run/php/php7.0-fpm.sock
我非常感谢与此问题相关的帮助或提示。
答案 0 :(得分:3)
你的while
语句后面有一个额外的分号,导致整个明显的身体被忽略:
while (zahl <= 10); // <-- REMOVE THIS SEMICOLON
{
j = 0;
while (j++ < 5)
{
Console.WriteLine("{0,5}", root = (root + (zahl / root)) / 2);
}
}
答案 1 :(得分:0)
我建议将while
个圈转换为for
个圈:
static void Main(string[] args) {
// for each number in [0..10] range
for (double number = 1.0; number <= 10.0; ++number) {
double root = number / 2.0; // <- initial (zeroth) root aproximation
// we want to calculate 5 approximations:
for (int app = 1; app <= 5; ++app) {
root = (root + number / root) / 2.0;
// string interpolation $"..{some value} .." can be very handy
Console.WriteLine($"sqrt({number}) == {root} (app #{i})");
}
// Let's split output
Console.WriteLine();
}
}
小心
while (zahl <= 10) {...}
应在zahl
内更改{...}
以防止无限循环 while (zahl <= 10);
表示“zahl&lt; = 10时不执行任何操作”会导致无限循环 结果:
sqrt(1) == 1.25 (approximation #1)
sqrt(1) == 1.025 (approximation #2)
sqrt(1) == 1.00030487804878 (approximation #3)
sqrt(1) == 1.00000004646115 (approximation #4)
sqrt(1) == 1 (approximation #5)
sqrt(2) == 1.5 (approximation #1)
sqrt(2) == 1.41666666666667 (approximation #2)
sqrt(2) == 1.41421568627451 (approximation #3)
sqrt(2) == 1.41421356237469 (approximation #4)
sqrt(2) == 1.41421356237309 (approximation #5)
sqrt(3) == 1.75 (approximation #1)
sqrt(3) == 1.73214285714286 (approximation #2)
sqrt(3) == 1.73205081001473 (approximation #3)
sqrt(3) == 1.73205080756888 (approximation #4)
sqrt(3) == 1.73205080756888 (approximation #5)
....
sqrt(9) == 3.25 (approximation #1)
sqrt(9) == 3.00961538461538 (approximation #2)
sqrt(9) == 3.00001536003932 (approximation #3)
sqrt(9) == 3.00000000003932 (approximation #4)
sqrt(9) == 3 (approximation #5)
sqrt(10) == 3.5 (approximation #1)
sqrt(10) == 3.17857142857143 (approximation #2)
sqrt(10) == 3.16231942215088 (approximation #3)
sqrt(10) == 3.16227766044414 (approximation #4)
sqrt(10) == 3.16227766016838 (approximation #5)