简体   繁体   English

输入一个scanf()的值,但没有任何反应

[英]Input a value for a scanf(), but nothing happens

I'm writing some code as part of a few assignment exercises to learn C programming from absolute basics, and I've run into a problem, which is probably quite simple to solve, but I'm completely stuck! 我正在写一些代码,这是一些从绝对基础上学习C编程的赋值练习的一部分,但我遇到了一个问题,该问题可能很容易解决,但我完全陷入了困境! I'm writing a program to implement a basic Newton's method for differentiation. 我正在编写一个程序来实现牛顿微分的基本方法。 Whenever I input an initial value to the scanf(), the program simply stops, doesn't return anything, terminate or freeze. 每当我向scanf()输入初始值时,该程序就会停止,不返回任何内容,终止或冻结。 Any help would be great. 任何帮助都会很棒。 Here is my code to start with: 这是我的代码开头:

 #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>

//function to be used f(x) = cos(x)-x^3

//f'(x) = -sin(x)-3x^2

int main()
{
  double x, xold;
  printf("Enter an initial value between 0 and 1\n");
  scanf("%lf",&xold);
  double eps = 1e-12;
   x = xold - ((cos(xold)-pow(xold,3))/(-(sin(xold)-(3*pow(xold,2)))));
    while (fabs(x-xold)>eps)
    {
    x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2))));
    }
    printf("The answer is %.12lf",x);
    return 0;
};

In your while loop: 在您的while循环中:

x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2))));

the value of the = right operand is always the same, how could you exit the loop once you enter it? =右操作数的值始终相同,一旦输入循环,如何退出循环?

Actually the thing is you are not updating your xold variable. 实际上,您没有更新xold变量。 Try the below modified code for your problem, see if I have done correctly: 请尝试以下修改后的代码解决您的问题,看看我是否做得正确:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


int main()
{
    double x, xold;
    printf("Enter an initial value between 0 and 1\n");
    scanf("%lf",&x);
    double eps = 1e-12;

    x = x - ((cos(x)-pow(x,3))/(-(sin(x)-(3*pow(x,2)))));
    while (fabs(x - xold)>eps)
    { 
        xold = x;
        x = x - ((cos(x)-pow(x,3))/(-sin(x)-(3*pow(x,2))));
    }
    printf("The answer is %.12lf\n",x);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM