我已经不知疲倦地试图做到这一点,但似乎没有任何效果。我做的很多事情都让我误以为“控制可能会达到无效功能的终结”。
基本上,我们创建了一个输出燃气使用统计数据的程序。我坚持的是: “在4年的时间内,天然气的价格将从定义的初始值上升到规定的最终值,然后在接下来的4年内保持固定在更高的值。”
我觉得应该有一个循环或函数,但每次我将NUM_YEARS设为int而不是const,无论程序告诉我'控件可能达到非空函数的结束。'
以下是该计划:
#include <cstdlib>
#include <iostream>
using namespace std;
const int MILES_PER_YEAR = 21000;
const double CITY_PERCENT = 45.0;
const double HIGHWAY_PERCENT = 55.0;
const double CITY_MPG = 51.0;
const double HIGHWAY_MPG = 45.0;
const double USABLE_GAS = 9.0;
const double INITIAL_PRICE = 3.359;
const double FINAL_PRICE = 6.00;
const int NUM_YEARS = 8; //This will be the total number of years
double gasPrice(int day);
int main(int argc, char * argv[]) {
cout << "Driving the Toyota Prius" << endl;
double daily_miles = MILES_PER_YEAR / 365.0;
double daily_city_miles = daily_miles * CITY_PERCENT/100.0;
double daily_highway_miles = daily_miles*HIGHWAY_PERCENT/100.0;
double daily_gas_consumed = daily_highway_miles / HIGHWAY_MPG +
daily_city_miles / CITY_MPG;
double gas_in_tank = USABLE_GAS;
double price;
double amount_purchased;
double gallons_purchased;
double total_gas_purchases = 0;
for(int day = 0;day < 365*8; day++) { //If the day is less than the total number of days in 8 years, add one day
cout << "Driving summary for day " << day << endl;
cout << " highway miles: " << daily_highway_miles << endl;
cout << " city miles : " << daily_city_miles << endl;
cout << " gas consumed : " << daily_gas_consumed << endl;
gas_in_tank = gas_in_tank - daily_gas_consumed;
cout << " gas in tank : " << gas_in_tank << endl;
if (gas_in_tank < 0.0) {
cout << " BUY GAS" << endl;
gallons_purchased = USABLE_GAS - gas_in_tank;
price = gasPrice(day);
cout << " price today is : " << price << endl;
cout << " Gallons purchased: " << gallons_purchased << endl;
cout << " fillup cost : " << gallons_purchased * price << endl;
total_gas_purchases = total_gas_purchases + gallons_purchased * price;
cout << " total gas cost : " << total_gas_purchases << endl;
gas_in_tank = USABLE_GAS;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
double gasPrice(int day, int YEAR_NUM) {
if (int day=365) { //call YEAR_NUM, for day=365, increase YEAR_NUM by 1
YEAR_NUM++;
day = 0;
}
if (YEAR_NUM >= 4) {
double currentPrice = FINAL_PRICE;
currentPrice;
}
if (YEAR_NUM < 4) { //conditional price for the first four years
double dailyIncrease = (FINAL_PRICE - INITIAL_PRICE) / (NUM_YEARS * 365);
double currentPrice = (INITIAL_PRICE + day * dailyIncrease);
return currentPrice;
}
}
答案 0 :(得分:2)
您需要在gasPrice
循环之外的for
中返回一些内容。编译器说有可能不会满足while
条件,在这种情况下没有值可以返回。
另一方面,while
循环对它们的编写方式没有多大意义。只需要他们if
语句。
答案 1 :(得分:1)
我认为如果你移动&#34;返回currentPrice;&#34;在这两个while循环中,它将解决问题。
答案 2 :(得分:0)
函数gasPrice
在for循环之外没有return语句。由于函数的返回类型不是void,因此如果不存在return语句,则函数的行为将是未定义的。