2014-04-23 67 views
0

我能夠打印出每個銷售人員的總和,但是每個人對於一個產品的數學計算有點偏離。有人能爲我指出這個明顯的錯誤嗎? 爲「Albatross.txt」文件訪問https://www.dropbox.com/s/itxiuabj25r8j45/Albatross.txt閱讀數據文件,用給出的數據計算總和

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

    int main(){ 

    FILE*fp; 
    fp=fopen("Albatross.txt", "r"); 
    if (fp==NULL){ 
     printf ("Error: can't open file.\n");} 
    else{ 
     printf ("File opened successfully.\n");} 

    int person, 
     product, 
     price, 
     total, 
     sum; 

    printf("File Contents: \n"); 
    int i,j=1; 
    //int A[person][product][price]; 
    for (i = 0; i<20; i++) 
    { 
     int A[person][product][price]; 
     fscanf(fp, "%d" "%d" "%d", &person, &product, &price); 
     printf ("%d %d %d\n", person, product, price); 

    } 
    for (i=1; i<5; i++){ 
     total = total + price; 

     printf("Salesperson %d : \t%d\n", i,total); 
    } 

    return 0; 
    } 
+1

你是不是在做實際銷售每個銷售人員的總和是不是?嘗試將值更改爲隨機值。 'total = total + price;'取決於銷售員的最後一個條目4. – Prabhu

+1

你實際上設法編譯了這個?行A [人] [產品] [價格]是錯誤的。您可能需要閱讀以下內容:http://www.tutorialspoint.com/cprogramming/c_arrays.htm我懷疑您打算爲每個銷售人員添加5種產品,並因此添加一行:for(i = 1; i <5; i ++ )應該是:for(i = 0; i <5; i ++) –

回答

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

#define NUM_OF_REC 20 
#define NUM_OF_PSN 5 //+1 , 0 is dummy 

typedef struct rec { 
    int person; 
    int product; 
    int price; 
} Record; 

int main(){ 
    FILE*fp; 
    fp=fopen("Albatross.txt", "r"); 
    if (fp==NULL){ 
     printf ("Error: can't open file.\n"); 
     return EXIT_FAILURE; 
    } else{ 
     printf ("File opened successfully.\n"); 
    } 

    Record A[NUM_OF_REC]; 
    int total[NUM_OF_PSN] = {0}; 

    printf("File Contents: \n"); 
    int i; 
    for (i = 0; i < NUM_OF_REC; i++){ 
     fscanf(fp, "%d %d %d", &A[i].person, &A[i].product, &A[i].price); 
     printf ("%d %d %d\n", A[i].person, A[i].product, A[i].price); 
     total[A[i].person] += A[i].price; 
    } 
    fclose(fp); 
    for (i=1; i< NUM_OF_PSN; i++){ 
     printf("Salesperson %d : \t%d\n", i, total[i]); 
    } 

    return 0; 
} 
+0

謝謝!這非常有幫助!特別是使用陣列的正確方法!我也有點懷疑。 – user2093028