【问题标题】:Why does my program keep returning the input prompt?为什么我的程序一直返回输入提示?
【发布时间】:2014-11-17 19:08:07
【问题描述】:

这段代码编译得很好,但是当我运行它时,在第二个“scanf”上它总是会返回提示,就像它期望无限数量的值一样。我在 Linux 上使用 Clang。我真的需要你的帮助,因为我这周五要考试。

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

int fatorial(int n){
    int f=1, t;
    for(t=n;t>1;t--){
        f=f*t;
    }
    return f;
}

float sen(float x, float tol){
    float res=0, aux=0;
    int n=0;
    for(n=1;res-aux!=tol||aux-res!=tol; n++){
        res=aux;
        res=res+(pow(-1,n+1))*((pow(x,2*n-1))/fatorial(2*n-1));
    }
    return res;
}
int main(){
    float yo, tol, res;
    printf("What's the value of x? ");
    scanf(" %f", &yo);
    printf("What's the tolerance? ");
    scanf(" %f", &tol);
    res=sen(yo, tol);
    printf("The sin of %.2f is %f.\n", yo, res);
    return 0;
}

【问题讨论】:

  • 你能解释一下“总是返回提示”是什么意思吗?不清楚你的意思是什么。
  • 当然 ^-^ 基本上它会问“公差是多少?”我输入了一个数字,然后按回车,它不断要求在新行中输入一个数字。
  • 您使用什么输入值?也许您可以显示您所看到的屏幕截图?您的代码的输入部分没有循环,因此不清楚它如何可能会多次询问。
  • link 这有帮助吗?

标签: c linux clang prompt


【解决方案1】:

根据您链接的屏幕截图,您的程序没有要求更多输入。它正在计算答案。在 Linux 中,您仍然可以在程序运行时在终端中输入内容,这就是您正在做的事情。

您可以使用top 或其他 CPU 监视器来查看您的进程正在使用 100% 的 CPU。问题是您在sen() 中的算法正在运行一个无限循环,并且从未达到其目标容差值。

【讨论】:

  • -_- 真的吗?!那?!它总是小事...基本上我把 aux 放在 res 之后,当它应该是 aux=res...
【解决方案2】:

试试这个

float sen(float x, float tol){
    float res=0, aux=tol+1;
    int n;
    for(n=0;fabsf(res-aux)>tol; n++){
        aux=res;
        res=res+pow(-1, n)*pow(x, 2*n+1)/fatorial(2*n+1);
    }
    return res;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2011-12-08
    相关资源
    最近更新 更多