读取数据文件,使用给定的数据计算总和

时间:2014-04-23 05:48:59

标签: c

我能够打印出每个销售人员的总和,但每个人的产品数量有点偏差。有人可以为我指出这个明显的错误吗? 访问https://www.dropbox.com/s/itxiuabj25r8j45/Albatross.txt以获取" 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 个答案:

答案 0 :(得分: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;
}