2013-05-22 140 views
1

我必须从main创建并调用一个函数。然后我必须调用scanf来读取两个整数并打印出更大的整数。然后我必须做另一个scanf,但这次用双打而不是整数。有没有办法使用scanf和“if”和“else”语句?

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的工作?谢谢。

+0

如果scanf函数的返回值==无参数的你再通过它的成功别人的错误 –

回答

1

在你的情况,你可以检查scanf()是否已经成功地或者没有工作如下,

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

scanf()返回的参数个数successfuly阅读通过它。

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

它说你试图从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; 
} 
+0

OH!很好,赶上,谢谢!是的,我必须创建一个名为“read_example”的函数。 :) 谢谢! – Karen

+0

如果我只创建一个函数呢?当他说“添加一个scanf来阅读两个双打......”,这是否意味着为双打添加另一个功能?我有点困惑,因为在方向上,他只告诉我们做一个叫做“read_example”的函数。 ( – Karen

+0

)你可以做一切从一个函数,甚至打印两个整数中的较大者 我只是创建了void read_example(void); 然后你可以做double和int scanf并打印在一个函数 – Trent

0

sollution为

我要创建并从主调用函数。然后我必须调用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;` 
    }