2014-11-02 23 views
-2

我在這裏遇到問題。我正在嘗試從用戶處獲得幾個輸入,並根據他工作的天數計​​算總輸入和平均值。例如,如果他工作了10天,當他輸入10時,程序會要求他輸入10天的工作時間。 iterateArray數組只能保存最多30天和變量天數,並保存輸入的天數。我怎樣才能得到使用scanf的值?使用scanf獲取用戶的幾個輸入

int main(void){ 

    printf("The program calculates the total hours worked during\n"); 
    printf("a specific period and the average length of a day.\n\n"); 
    printf("How many days:"); 

    scanf("%d",&days); 


    do{  
      if(i==days){ 
      break; 
      i++; 
     } 


    else{ 
     printf("Enter the working hours for day %d:",++i); 
     scanf("%f",&iterateArray[0]); 
     } 

    }while(i<days); 


} 
+0

您的代碼並不顯示'i'或'iterateArray'的定義。你還應該檢查'scanf()'操作是否成功,而不是簡單地假定它們工作。你的代碼縮進留下了很多不盡人意的地方。我相信你可以使用'for'循環來代替'do ... while'循環,這會讓你的代碼更容易理解。 – 2014-11-02 06:02:47

回答

1

我覺得你在尋找這樣的事情:

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

int main(){ 

    int days, dayCount; 
    double iterateArray[30], totalWork = 0, averageWork = 0; 

    printf("The program calculates the total hours worked during\n"); 
    printf("a specific period and the average length of a day.\n\n"); 
    printf("How many days: \n>"); 

    scanf(" %d", &days); 

    if (days > 30) { 
     printf("You can't work longer then 30 days!"); 
     exit(0); 
    } 

    for(dayCount = 0; dayCount < days; dayCount++) { 
     printf("Enter the working hours for day %d:", dayCount+1); 
     scanf(" %lf", &iterateArray[dayCount]); 
     totalWork += iterateArray[dayCount]; 
    } 

    averageWork = totalWork/days; 

    printf("\nThe total hours you worked is: %.2lf\n", totalWork); 
    printf("The average length of a day is: %.2lf\n", averageWork); 


    return 0; 

} 
+0

理想情況下,您應該檢查'scanf()'的返回值以確保成功。 – 2014-11-02 06:03:58

+0

感謝喬納森的回覆。其實我有計算總小時數和平均值的功能,但問題是要得到輸入。我使用一個變量來獲取輸入並將其傳遞給數組,它不起作用,我在scanf中使用了數組,它不起作用,最後我使用了一個for循環,但它不起作用 – Sagnol 2014-11-02 16:02:58

+0

@薩尼奧爲你做了我的代碼工作並解決了你的問題或者現在沒有工作? – Rizier123 2014-11-02 16:04:18