有没有办法将scanf与“if”和“else”语句一起使用?

时间:2013-05-22 06:55:19

标签: c scanf

我必须从main创建并调用一个函数。然后我必须调用scanf读取两个整数并打印出更大的整数。然后我必须做另一个scanf,但这次是双打而不是整数。

int main()
{
   int x, y;
   scanf("%d%d", &x, &y);

   if (x > y)
   {
      printf("%d", x);
   }

   scanf("%lf%lf", &w, &z);

   if ( w > z)
   {
      printf("%f", w);
   }

   return 0;
}

我不确定我是否做得对,我如何检查返回值以查看scanf是否有效?感谢。

4 个答案:

答案 0 :(得分:3)

how would I check the return value to see that the scanf worked? 

通过检查scanf()的返回值。

  if( scanf("%d%d", &x, &y) != 2) 
  {
   /* input error */ 
  }

   if (x > y)
   {
      printf("%d", x);
   }

   if(scanf("%lf%lf", &w, &z) != 2) 
   { 
   /* input error */
   }

   if ( w > z)
   {
      printf("%f", w);
   }

来自scanf()文档:

   These functions return the number of input items successfully matched
   and assigned, which can be fewer than provided for, or even zero in
   the event of an early matching failure.

   The value EOF is returned if the end of input is reached before
   either the first successful conversion or a matching failure occurs.
   EOF is also returned if a read error occurs, in which case the error
   indicator for the stream (see ferror(3)) is set, and errno is set
   indicate the error.

答案 1 :(得分:1)

在您的情况下,您可以按照以下方式检查scanf()是否成功运作,

if( scanf("%d%d", &x, &y) == 2)
{
   if (x > y)
   {
       printf("%d", x);
   }
}
else
{
   printf("\nFailure");
}

scanf()返回它成功读取的参数数量。

答案 2 :(得分:1)

它说你正试图从main调用一个函数。这是否意味着你的老师想要除了主要的功能?在这种情况下,您想要创建一个如下所示。您还必须使用双整数执行类似的操作。

#include stdio.h

int bigger(void);

int main(void)
{
int larger;
larger = bigger(void);
printf("The Larger integer is: %d\n", larger);

return 0;
}

int bigger(void)
{
int x,y,z;
printf("Enter your first integer\n");
scanf("%d", &x);
printf("Enter your second integer\n");
scanf("%d", &x);

if(x > y)
{
z = x;
}
else
{
z = y;
}
return z;
}

答案 3 :(得分:0)

sollution for

我必须从main创建并调用一个函数。然后我必须调用scanf读取两个整数并打印出更大的整数。然后我必须做另一个scanf,但这次使用双精度而不是整数。* /

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

   int main(){
   int a,b;
   printf("enter any two numbers");
   scanf(" %d\n %d",&a,&b);
   if(a>b){
        printf("bigger number is %d",a);
        }else{
              printf("bigger number is %d\n",b);        
               }    
    float c,d;
    printf("enter any two numbers");
    scanf(" %f\n %f",&c,&d);
    if(c>d){
      printf("bigger number is %.2f",c);
      }else{
          printf("bigger number is %.2f\n",d);        
              }               
   system("pause");
   return 0;`
    }