计算油耗--数组使用示例
程序代码:
//计算油耗--数组使用示例 #include <iostream> #include <iomanip> using namespace std; int main ( ) { const int MAX = 20; double gas[ MAX ]; long miles [ MAX ]; int count = 0; char indicator = 'y'; //默认值设为 'y',在下面的 while 循环中要用到 while((indicator == 'y' || indicator == 'Y') && count < MAX) { cout << endl << "Enter gas quantity: "; cin >> gas[count]; //输入购买的汽油 cout << "Enter odometer reading: "; cin >> miles[count]; //跑了多少路程 ++count; //计数器自加 1 cout << "Do you want to enter another( y or n)? "; cin >> indicator; //循环计算 } if( count <= 1) //如果只输入一对数据,则无结果退出 { cout << endl << "Sorry - at least two readings are necessary. "; //system("pause"); return 0; } for( int i = 1; i < count; i++) //计算次数 i 小于 count ,比如 count 为 4, i 为 3 { cout << endl << setw(2) << i << "." << "Gas purchased = " << gas[i] << "Gallons " << "resulted in " << ( miles[i] - miles[i-1]/gas[i]) << " miles per gallon."; cout << endl; } system("pause"); return 0; }MAX的值可以根据情况指定