【问题标题】:When i try to give 3 inputs to my program , it needs 4 to run properly. Why is that?当我尝试为我的程序提供 3 个输入时,它需要 4 个才能正常运行。这是为什么?
【发布时间】:2019-06-08 09:15:51
【问题描述】:
#include <stdio.h>
#include <stdlib.h> 
#define f(x) (1 / (x*x+1))



int main(){
    double a,b,h,x,y;

    printf("Enter a, b, h:  ");
    scanf(" %lf %lf %lf " , &a, &b, &h);

// I ask for 3 inputs but the programm needs 4 to run...why is that?


    x = a;

     while(x<b)
     {

        y = f(x);
        printf("%lf %lf \n", x ,y );
        x +=h;

     }


    system("Pause");
    return(0);  

}

【问题讨论】:

  • 你的问题在哪里?
  • @EdChum 在标题中。
  • @LightnessRacesinOrbit 我更喜欢亲自提出问题
  • @EdChum 这是性别歧视!
  • Seems to work okay。你没有按 来提交来自终端的输入吗?请提供有关如何重现您的问题的更多信息。

标签: c++ dev-c++


【解决方案1】:

问题出在你的 scanf 上:

scanf(" %lf %lf %lf " , &a, &b, &h);
                   ^

scanf 需要查看下一个非空格来确定这个“0 个或多个空格”的结尾,所以你必须给出第 4 个值(它可以是垃圾 - 只要它不是空格)让scanf 终止输入。

如果您使用的是 Windows,则可以在新行上按 Ctrl-Z 并按 Enter。这将向程序发送一个 EOF,该程序也可以终止输入。 (我想您使用的是 Windows,因为我在您的程序中看到了 system("pause")

【讨论】:

  • 是的,就是这样。好的经验法则是使用前导空格,而不是尾随空格。
  • @CorrurtedDisciple 您可以单击此答案旁边的灰色勾号将其标记为“已接受”。
  • 为了避免出现 OS-ist,您可以提到在 UNIX 系统上 ctrl-D 会向程序发送 EOF。
猜你喜欢
  • 2022-12-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多