从文件中读取并进行计算。 C程序

时间:2013-11-19 07:39:52

标签: c

我需要编写C程序,从文件中读取车号,行驶里程和使用的加仑数。计算每加仑英里数。计算总数和平均MPG。

我只需要帮助计算每加仑英里数。

In output should be :20    But my output is: 1966018914
                     25                      20
                     24                      25
                     23                      24

任何人都可以看到我的代码并帮我搞清楚吗?!

这是代码:

int main()
{
    int car, miles, gas;
    int sumMiles = 0;
    int sumGas = 0;
    int avgMPG = 0;
    FILE *inFile, *outFile;
    char fname[20];

    printf("Enter a file name: ");
    gets(fname);

    inFile = fopen(fname, "r");
    if (inFile == NULL)
    {
        printf("\nFailed to open file.\n");
        exit(1);
    }

    outFile =  fopen("output.txt","w");

    if(outFile==NULL)
    {
        printf("The file was not opened.");
        exit(1);
    }

    printf("\nCar No.   Miles Driven    Gallons Used\n");

    while (fscanf(inFile, "%d %d %d",&car, &miles, &gas) != EOF)
    {
        printf("%-7d %-15d %d\n",car,miles,gas);
        sumMiles += miles;
        sumGas += gas;
        avgMPG = sumMiles / sumGas;
    }

    printf("\nThe total miles driven is %d\n", sumMiles);
    printf("The total gallons of gas used is %d\n", sumGas);
    printf("The average miles per gallon of gas used is %d\n", avgMPG);

    printf("File copied succesfully!");
    fclose(inFile);
    fclose(outFile);

}

这是输入文件:

123 100 5
345 150 6
678 240 10
901 350 15

3 个答案:

答案 0 :(得分:0)

您的计划工作正常:IdeOne demo

我对您的代码所做的就是删除输入和输出文件,并将其替换为IdeOne所需的stdinstdout。此外,您似乎没有在任何地方使用输出文件。

答案 1 :(得分:0)

输入:

123 100 5
345 150 6
678 240 10
901 350 15

输出:

Car No.   Miles Driven    Gallons Used
123     100             5
345     150             6
678     240             10
901     350             15

The total miles driven is 840
The total gallons of gas used is 36
The average miles per gallon of gas used is 23

您的代码可以与除您之外的其他人一起使用。问题可能出在环境中。你的文本编辑器中有异国情调的编码吗?你是在离开流浪汉,缩进等吗?

答案 2 :(得分:-1)

您的代码运行正常。您一直在代码中使用printf,它无法将输出写入您需要使用fprint的文件。 请查看下面的代码,该代码可以根据需要使用。

int main()
{
int car, miles, gas;
int sumMiles = 0;
int sumGas = 0;
int avgMPG = 0;
float ans=0;
FILE *inFile, *outFile;
char fname[20];

printf("Enter a file name: ");
gets(fname);

inFile = fopen(fname, "r");
if (inFile == NULL)
{
    printf("\nFailed to open file.\n");
    exit(1);
}

outFile =  fopen("output.txt","w");

if(outFile==NULL)
{
    printf("The file was not opened.");
    exit(1);
}

while (fscanf(inFile, "%d %d %d",&car, &miles, &gas) != EOF)
{
    sumMiles += miles; // not needed acc to output
    sumGas += gas; // not needed acc to output
    avgMPG = sumMiles / sumGas; // not needed acc to output
    ans = miles/gas;
    fprintf(outFile,"%f\n",ans);
}

fclose(inFile);
fclose(outFile);

}