首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >整个MPG的输出是部分关闭的(Visual C++)

整个MPG的输出是部分关闭的(Visual C++)
EN

Stack Overflow用户
提问于 2015-09-26 21:05:31
回答 1查看 231关注 0票数 1

我创建了一个程序,在这个程序中,你可以输入每一个油罐车行驶的里程和加仑,这个程序会显示每一个油罐车的mpg。我正在使用2010。当我输入-1的前哨值时,就会得到整个mpg。这是我的代码:

代码语言:javascript
复制
/* Name
Lab 3 - Page 105, 3.16
September 23th, 2015
Page 2 of 3 */

#include "stdafx.h"
#include <iostream>
#include <stdio.h>

// function main begins program execution
int main( void )
{   
    // initialization phase
    unsigned int counter = 0; // number of tanks used
    float gallons = 0; // gallons
    float miles = 0; // miles
    float milesPerGallon = 0; // MPG
    float allTankMPG = 0; // sum of all tanks (MPGs)

    float averageMPG = 0; // average MPG of all tankfuls

    // processing phase
    // get first tankful information
    printf( "%s", "Enter the gallons used (-1 to end): " ); // prompt for gallons used
    scanf( "%f", &gallons ); // read gallons input from user

    // loop while sentinel value not yet read from user
    while ( gallons != -1 ) {

        printf( "%s", "Enter the miles driven: " ); // prompt for miles driven
        scanf( "%f", &miles ); // read miles input from user

        milesPerGallon = miles / gallons; // miles per gallon for the tank
        printf("%s%.6f\n\n", "The miles/gallon for this tank was: ", milesPerGallon ); // display milesPerGallon
        counter = counter + 1; // increment counter
        allTankMPG = allTankMPG + milesPerGallon; // add the miles per gallon the sum total of every tank's mpg

        // get next tankful information
        printf( "%s", "Enter the gallons used (-1 to end): " ); // prompt for gallons used
        scanf( "%f", &gallons ); // read input of the next gallon from user
    } // end while

    // termination phase
    // if user entered at least one set of information for one tankful
    if ( counter != 0 ) {

        // calculate average MPG of all tankfuls
        averageMPG = (float) allTankMPG / counter; // avoid truncation

        // display average with six digits of precision
        printf( "\n%s%.6f\n\n", "The overall average miles per gallon was ", averageMPG );
    } // end if

    system( "pause" );
    return 0;
} // end function main``

但是,我的输出如下所示:

  • 输入所用加仑(-1至结尾):12.8
  • 输入行驶里程: 287
  • 这个油箱的哩数是: 22.421875英里。
  • 输入所用加仑(-1至结尾):10.3
  • 输入行驶里程: 200英里
  • 这个油箱的哩数是: 19.417475英里。
  • 输入所用的加仑(-1至结尾):5
  • 输入行驶里程: 120英里
  • 这个油箱的哩数是: 24.000000英里。
  • 输入所用加仑(-1至结尾):-1

每加仑的总平均里程是21.946449英里。

按任意键继续。。。

现在根据这本书,当输入相同的精确输入时,总的平均MPG应该是21.601423,而不是21.946449。有谁能详细解释一下为什么我的产量会略有下降呢?谢谢,非常感谢。

EN

回答 1

Stack Overflow用户

发布于 2015-09-26 21:20:17

这本书要你计算整个旅程中每加仑的平均里程,而不是不管长度如何,腿的平均重量都是一样的。为此,保留总里程和总加仑的总和。

顺便说一句,这是一个好主意,做双精度的计算,即使当你存储在一个浮动。这将使舍入错误最小化。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32802017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档