即使在写入printf(“ ...”)之后也没有收到输出

时间:2019-03-04 10:39:06

标签: c++

我已经编写了一个代码来查找数字的倒数,而无需使用除法,而是使用二等分法对其进行近似。有两个疑问。一,我应该保留x的下限和上限吗?还有没有一种更快的方法可以从极限收敛到所需值(输入的倒数),而不是仅仅求平均值?还有一个主要的疑问,当我尝试运行它时,它会在收到用户输入的数字后停止运行。有什么提示可以解决吗?

代码如下:

#include<stdio.h>
#include<cstdlib>
#define epsilon 0.0001
float f(float x, float &m)
{
    if(m==0)
    {
        printf("Reciprocal not defined");
        return 0.0;
    }
    else
    {
        return x+1/m;
    }
}
int main(void)
{
    float m,g1,x,g2,c;
    printf("Enter a number:\n");
    scanf("%f",f(x,m));
    g1=epsilon;
    g2=m;
    while(abs(f(g1,m)-f(g2,m))>epsilon)
    {
        c=(g1+g2)/2;
        if(f(g1,m)*f(c,m)<0)
        {
            g2=c;
        }
        else if(f(c,m)*f(g2,m)<0)
        {
            g1=c;
        }
    }
    printf("The reciprocal is approximately %f",c);

}

该代码预计将按以下方式工作:

Enter a number: 5
The reciprocal is approximately 0.2
Enter a number: 0
Reciprocal is not defined

相反,它显示:

Enter a number:
Reciprocal is not defined            

(不接受任何输入)

1 个答案:

答案 0 :(得分:4)

您的总体代码太复杂了,您对scanf的使用没有任何意义。

您可能想要这样的东西:

#include <stdio.h>
#include <cstdlib>
#include <cmath>

#define epsilon 0.0001f

int main(void)
{
  float m, g1, g2, c, diff;
  printf("Enter a number:\n");
  scanf("%f", &m);

  g1 = epsilon;
  g2 = m;

  do
  {
    c = (g1 + g2) / 2;
    diff = c * m - 1.0f;
    if (diff > 0)
      g2 = c;
    else
      g1 = c;
  } while (fabs(diff) > epsilon);

  printf("The reciprocal is approximately %f", c);
}

对于您的问题“ 还有一种更快的方法可以将限制从收敛到所需值(输入的倒数),而不是仅仅求平均值?”,我不知道,但是在搜索按等分通常相当快。

用于测试一系列值的测试程序:

#include <stdio.h>
#include <cstdlib>
#include <cmath>

#define epsilon 0.0001f

int main(void)
{
  float g1, g2, c, diff;

  for (float m = 1; m < 20; m += 1)
  {
    g1 = epsilon;
    g2 = m;

    do
    {
      c = (g1 + g2) / 2;
      diff = c * m - 1.0f;
      if (diff > 0)
        g2 = c;
      else
        g1 = c;
    } while (fabs(diff) > epsilon);

    printf("The reciprocal of %f is approximately %f vs. %f, diff %f\n", m, c, 1/m, c-1/m);
  }
}

Live demonstration