2013-05-22 138 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;` 
    }