用于计算平方根的自定义程序未显示任何输出 [英] Custom program to calculate sqare root isn't showing any output
问题描述
这是一个用户定义的程序,用于打印数字的平方根.它也应该适用于也不是完美平方的数字.每次将 i
递增 0.01
的步长,并检查 i * i
的值是否等于 n 代码>.如果相等,则打印
i
的值.
This is a user defined program to print the square root of a number. It is supposed to work for numbers which aren't perfect squares as well. i
is incremented by a step of 0.01
each time and the the value of i*i
is checked if equal to n
. And if equal then the value of i
is printed.
#include <stdio.h>
void squareRoot(double);
int main()
{
double num;
scanf("%lf", &num);
squareRoot(num);
return 0;
}
void squareRoot(double n)
{
double i;
for (i = 0; i < n; i += 0.01)
{
//printf("%.2lf\n",i*i);
if (i * i == n)
{
printf("%lf\n", i);
break;
}
}
}
推荐答案
由于注释中所说明的原因,您使用的方法充其量是非常不准确的,对于该示例我有几种计算平方根的方法将使用 巴比伦方法 使用简单的算术运算非常容易实现:
The method you use is, at best, very inaccurate for the reasons explained in the comments, there are several ways to calculate a square root, for this sample I'll use the Babylonian method which in its simplified form is very easy to implement using trivial arithmetic operations:
#include <stdio.h>
double squareRoot(double);
int main() {
double num;
printf("Enter number: \n");
scanf("%lf", &num);
if(num < 0) {
puts("Negative values not allowed");
return 1;
}
printf("Square root of %.2lf is %lf", num, squareRoot(num));
}
double squareRoot(double num) {
double sqroot = num / 2, temp = 0;
while (sqroot != temp) {
temp = sqroot;
sqroot = (num / temp + temp) / 2;
}
return sqroot;
}
这篇关于用于计算平方根的自定义程序未显示任何输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!