我创建了一个程序,在这个程序中,你可以输入每一个油罐车行驶的里程和加仑,这个程序会显示每一个油罐车的mpg。我正在使用2010。当我输入-1的前哨值时,就会得到整个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``但是,我的输出如下所示:
每加仑的总平均里程是21.946449英里。
按任意键继续。。。
现在根据这本书,当输入相同的精确输入时,总的平均MPG应该是21.601423,而不是21.946449。有谁能详细解释一下为什么我的产量会略有下降呢?谢谢,非常感谢。
发布于 2015-09-26 21:20:17
这本书要你计算整个旅程中每加仑的平均里程,而不是不管长度如何,腿的平均重量都是一样的。为此,保留总里程和总加仑的总和。
顺便说一句,这是一个好主意,做双精度的计算,即使当你存储在一个浮动。这将使舍入错误最小化。
https://stackoverflow.com/questions/32802017
复制相似问题