1

我必须从 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

4 回答 4

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.
于 2013-05-22T07:00:56.543 回答
1

在您的情况下,您可以检查是否scanf()成功,如下所示,

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

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

于 2013-05-22T07:01:26.213 回答
1

它说你正试图从 main 调用一个函数。这是否意味着您的老师想要除 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;
}
于 2013-05-22T07:10:53.703 回答
0

解决方案

我必须从 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;`
    }
于 2015-07-07T06:17:42.193 回答