我需要编写一个程序来计算遵循这些规则的行程距离
到目前为止这是我的程序
#include <iostream> //for cin >> and cout <<
using namespace std;
int main() // main algorithm
{
double distance;
double Milecost1;
double Milecost2;
double Milecost3;
double totalcost;
cout << "enter distance";
cin >> (distance);
void CFM();
if (distance >= 100) {
Milecost1 = 100 * 5.50;
} else {
totalcost = distance * 5.50;
}
void CSM();
if ( (distance >100) && (distance <= 500) ) {
Milecost2 = (distance - 100) *4.00;
}
void CTM();
if (distance > 500) {
Milecost3 = distance - 500 * 2.50;
}
void totalcost1();
totalcost = Milecost1 + Milecost2 + Milecost3;
cout << "the total cost for the distance travelled is" << totalcost
system("pause"); //to hold the output screen
return(0);
}
我的第一个问题是,计算成本的数学是否正确?
第二个问题是我运行该程序并且它说Milecost 2正在使用而没有被初始化我该怎么解决这个问题?
答案 0 :(得分:2)
不,数学不正确,例如使用distance = 501
,您将获得
Milecost1: 550
Milecost2: (unitialised)
Milecost3: 2.50
假设您更正了Milecost3
上的运算符优先级,因为您现在将乘以500乘以2.5并从distance
减去该值。
Milecost2
仅在distance
在其相关值范围内时分配,相反,0
应为distance <= 100
,并且distance > 500
时也应计算{{1}}如果我正确地理解了这个练习。
答案 1 :(得分:0)
我会把它写成:
#include <iostream> //for cin >> and cout <<
using namespace std;
int main() // main algorithm
{
double distance;
double Milecost1;
double Milecost2;
double Milecost3;
double totalcost;
cout << "enter distance";
cin >> (distance);
if (distance >= 100) {
Milecost1 = 100 * 5.50;
} else {
Milecost1 = distance * 5.50;
}
if ( (distance >100) && (distance <= 500) ) {
Milecost2 = (distance - 100) *4.00;
} else {
Milecost2 = 0;
}
if (distance > 500) {
Milecost3 = distance - 500 * 2.50;
} else {
Milecost3 = 0;
}
totalcost = Milecost1 + Milecost2 + Milecost3;
cout << "the total cost for the distance travelled is" << totalcost ;
system("pause"); //to hold the output screen
return(0);
}
摆脱对未定义函数的调用;并且不依赖于变量的初始化为0。
答案 2 :(得分:0)
我认为这应该可以正常使用
void main(void)
{
double distance;
double cost;
if(distance <= 100)
{
cost = distance * 5.50;
}
else if(distance > 100 && distance <= 500)
{
cost = 100 * 5.50;
cost += 4.00 * (distance - 100);
}
else
{
int temp = 100;
cost = temp * 5,50;
temp = 400;
cost += temp * 4.00;
temp = distance - 500;
cost += temp * 2.50;
}
}
答案 3 :(得分:0)
就个人而言,这就是我的方式:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
double distance;
cout << "Enter distance (Miles): ";
cin >> distance;
double milesOver500 = max(0.0, distance-500.0);
double milesInBetween = max(0.0, distance-milesOver500-100.0);
double milesUnder100 = max(0.0, distance-milesInBetween-milesOver500);
double totalCost = milesOver500 * 2.5 +
milesInBetween * 4.0 +
milesUnder100 * 5.5;
cout << "The total cost for the distance traveled is £" << totalCost << endl;
return 0;
}
在您的实施中,Milecost2
仅在条件(distance >100) && (distance <= 500)
为真时进行初始化,而不会始终如此。在上面的代码中,所有内容在声明时都会初始化,并且有一个有意义的值,以后不需要计算。事实恰恰相反,这种方法在这种情况下效果很好,但还有一些方法更难以这样做。当出现这种情况时,您应该尝试为声明时声明的每个变量分配一些有意义的默认值,如果出现某些条件,这些变量可能会发生变化。