2015-11-14 50 views
-4
#include<stdio.h> 

int calsum(int x, int y, int z); 

void main() 
{ 
    int a,b,c,i, sum; 
    for(i = 1; i <= 3; i++) 
     printf("\n Enter Number %d\n", i); 

    scanf("%d %d %d", &a, &b, &c); 
    sum= calsum(a,b,c); 
    printf("\nSum=%d", sum); 
} 

int calsum(int x, int y, int z) 
{ 
    int d; 
    d = x + y + z; 
    return (d); 
} 

您好,我想通過一個輸入數字之一,但我得到的輸出是.. 沒有得到所需的輸出。有人能告訴我解決方案嗎?

[email protected] ~/Desktop/C codes $ ./a.out 

Enter Number 1 

Enter Number 2 

Enter Number 3 

儘管我希望它問我一次輸入一個。請幫幫我。我對此很陌生。

+0

真正的問題更多的是考慮輸入大於輸出。 – ameyCU

回答

0

您可以使用數組爲

int a[3], i, sum; 
for (i = 0; i < 3 ; i++) 
{ 
    printf("\n Enter Number %d\n", i+1); 
    scanf("%d", &a[i]); 
} 
sum = calsum(a[0], a[1], a[2]); 
+0

剩下的代碼呢?即我應該對其他功能做些什麼改變? –

+0

Paul Ogilvie,我應該怎麼做calsum函數? –

+0

你能幫助我在功能上做出改變嗎? @haris –

0
  1. for僅環有它內部的一行代碼,

    printf("\n Enter Number %d\n", i); 
    

    所以輸出是正確的。

  2. main()必須返回int

  3. 必須檢查返回值scanf()
  4. 您可以使用類似這樣

    #include <stdio.h> 
    
    int calsum(int x, int y, int z); 
    int getinteger(); 
    
    int main() 
    { 
        int a, b, c, z; 
    
        a = getinteger(1); 
        b = getinteger(2); 
        c = getinteger(3); 
    
        z = calsum(a, b, c); 
    
        printf("\nSum = %d", z); 
    
        return 0; 
    } 
    
    int calsum(int x, int y, int z) 
    { 
        int d; 
        d = x + y +z; 
        return d; 
    } 
    
    int getinteger(int index) 
    { 
        int value; 
        printf("Enter the %dth number > ", index); 
        while (scanf("%d", &value) != 1) 
        { 
         int chr; 
         while (((chr = getchar()) != '\n') && (chr != EOF)) 
          continue; 
         printf("Invalid input -- try again\n"); 
         printf("Enter the %dth number > ", index); 
        } 
        return value; 
    } 
    
相關問題