Scanf 未接受双精度类型的输入

  • 本文关键字:类型 双精度 Scanf c
  • 更新时间 :
  • 英文 :


这是我正在运行的代码

#include <stdio.h>
#include <math.h>
void main()    
{
 int i=0;
 double kl,x0,x1,xk;
 printf("enter kl");
 scanf("%lf",&kl);  
 printf("hello");
 for(x1=kl;((x1-x0)>2) || ((x1-x0)<-2);x0 );  
  {
   x0=x1;
   x1=(x0/2.0)+(kl/(2.0*x0));
   }
 printf("%lf",x1); 
 printf(" %lf ",(sqrt(kl)-x1));
} 

运行后scanf不接收输入。不打印 Hello。

问题不在于scanf,它是一个无限循环(你的for循环有一个空体(。

编译器会告诉您:

d:tmp diciu$ gcc -g test2.c
[..]
test2.c:11:44: warning: for loop has empty body [-Wempty-body]
 for(x1=kl;((x1-x0)>2) || ((x1-x0)<-2);x0 );  
                                           ^ this semicolon creates the empty body
for 循环

末尾的分号告诉编译器生成一个具有空主体的 for 循环。

虽然阅读代码告诉您问题出在scanf,因为您没有看到打印的"hello"字符串,但您的假设不正确; stdout如果已缓冲,并且由于尚未刷新缓冲区而看不到字符串;您可以通过添加行终止符 ( printf("hellon") ( 或刷新标准输出(查找fflush(来强制刷新缓冲区。

即使您错过了编译器警告,使用调试器也很容易发现问题。

最新更新