我有一個變量total
,每次用戶輸入時都會存儲總里程和加侖數。使用相同變量從C語言while循環中獲得平均值
當用戶點擊-1時,程序會假設將所有總數加在一起並取平均值。 我無法獲得該變量,以便爲循環的下一次迭代添加前一個總值。我試過,但是它返回循環的最後總值?
我在做什麼錯?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
const float EXIT_VALUE = -1.0f;
int main(void)
{
float gallons; // number of gallons used
float miles; // number of miles driven
float totals; // total = miles * gallons
int numOfEntries = 0; // number of entries
float avgConsumption = 0; // avg of all entries made by user
// get number of gallons from user
printf("%s%.1f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
scanf("%f", &gallons);
// loops until user enter -1
while (gallons != EXIT_VALUE) {
//miles driven by user
printf("%s", "Enter the miles driven: ");
scanf("%f", &miles);
// calculate total miles per gallon
totals = miles/gallons;
printf("The miles/gallons for this tank was %.6f\n\n", totals);
// get number of gallons from user
printf("%s%.2f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
scanf("%f", &gallons);
totals += totals;
numOfEntries++;
avgConsumption = totals/numOfEntries;
} // end while
printf("\nThe overall average miles/gallon was %.6f: ", avgConsumption);
_getch();
return 0;
} // end main
'總額+ = totals'是一樣的由2乘以'totals'我敢肯定平均值不同 –
什麼,我的意思是說了,這裏的平均是在「avgConsumption =總計計算計算/ numOfEntries「,其中totals是循環的所有迭代中總計的總數,numOfEntries是用戶被要求輸入總數的次數 – Rgoat
而且正如我所說的,」總計「計算不正確 –