我创建了一个程序,您输入里程数和每个容器使用的加仑数,程序显示每个容器的mpg。我正在使用Visual Studio 2010.当我输入-1的sentinel值时,我将获得整体mpg。这是我的代码:
/* 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``
我的输出看起来像这样:
这个坦克的里程/加仑是:22.421875
输入使用的加仑数(-1到结束):10.3
这个坦克的里程/加仑是:19.417475
输入使用的加仑数(-1到结束):5
这辆坦克的里程/加仑是:24.000000
输入使用的加仑数(-1到结束): - 1
每加仑的总平均英里数为21.946449
按任意键继续。 。
现在根据这本书,当输入相同的输入时,总体平均MPG应为21.601423,而不是21.946449。任何人都可以详细说明为什么我的输出几乎没有关闭?谢谢,非常感谢。
答案 0 :(得分:1)
这本书要求你计算整个行程中每加仑的平均英里数,而不是长度的均衡加权平均值。为此,保留总里程和总加仑总和。
顺便说一句,以双精度进行计算是个好主意,即使你在浮点数中存储也是如此。这可以最大限度地减少舍入误差。