作为一项任务,我使用hi-lo方法编写了一个日志函数,以找到答案,但对于大于10的数字,我不起作用,我也不知道为什么
int main() {
double n, nq, x, y;
printf("Enter the number you wish to take to the base 10 logarithm:\n");
scanf("%lf", &x);
double hi = 1;
double lo = 0;
double qlo = 1;
double qhi = 10;
for(int i = 0; i <= 1000; i++) {
n = ((lo + hi)/2);
nq = sqrt(qlo * qhi);
if(nq > x) {
hi = n;
qhi = nq;
} else {
lo = n;
qlo = nq;
}
}
y = n;
printf("the logarithm is equal to %lf\n", y);
printf("%lf\n", log10(x)); // to check result
}发布于 2019-05-13 08:58:25
Enter the number you wish to take to the base 10 logarithm:
1234.5678
50 iterations found 3.091514945509见下面的变化..。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int main()
{
double x, y;
printf("Enter the number you wish to take to the base 10 logarithm:\n");
scanf("%lf", &x);
double hi = 1;
double lo = 0;
double qlo = 1;
double qhi = 10;
/*if (x <= 0) handle exception log undefined for input <= 0*/
double tmp = 0;
while (x > 10)
{
tmp++;
x /= 10;
}
int i;
double n = 0, nprev = -1;
for (i = 0; i <= 1000 && fabs(n - nprev) > 1.0E-15; i++)
{
nprev = n;
n = ((lo + hi) / 2);
double nq = sqrt(qlo * qhi);
if (nq > x)
{
hi = n;
qhi = nq;
}
else
{
lo = n;
qlo = nq;
}
}
y = tmp + n;
printf("%2d iterations found %.12f",i,y);
}发布于 2019-05-13 07:29:14
在将qhi设置为10时,您已经将结果限制为10。将hi设置为1也没有帮助。因此,任何大于10的输入都将返回值1。
如果您希望您的函数使用更大的域,您需要更明智地选择hi、lo、qlo和qhi。
https://stackoverflow.com/questions/56107527
复制相似问题