I am no veteran either but I think I made you program work to my knowledge.
The statement :
if(numberOfMiles>100^numberOfMiles<=500)
makes no sense to me. Were you trying to say (is miles is inbetween 100 and 500) ? if so, notice how I changed it. You can replace the keyword
and
with
&&
if you like. They both mean the same thing in C++.
You were also re-declaring the float variable "variableShippingCost" on lines 31, 34, and 37. Once you declare a variable to be a certain data type, you only need to use the identifier (variable name) to reference it from then on until you want to declare an entirely new variable. When you were re-declaring them you should have gotten a compiler error but since you were doing this in an if statement those variables were considered a part of each own's if statement, meaning once the if statement executed, that variable was destroyed.
I think you should grab a book on C++ or even C, and read up on scope. It isn't complicated but it is extremely important to understand when it comes to writing functional code.
And global variables are not something you should use freely. They may seem harmless now, but if you start to write big programs they can really screw you over. I only use global variables for testing. There is always a better way to scope all of your variables.
Hope this helps.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
float numberOfMiles; //literal constant
float variableShippingCost; //global variables
int calculateVariableCost() {
if (numberOfMiles <= 100)
variableShippingCost = (numberOfMiles * 5);
if (numberOfMiles > 100 and numberOfMiles <= 500)
variableShippingCost = (((numberOfMiles - 100)* 4)+500);
if (numberOfMiles >= 500)
variableShippingCost = (((numberOfMiles - 500)* 3)+900);
}
int main () {
cout << "Enter the number of miles:";
cin >> numberOfMiles;
if (numberOfMiles < 0)
cout << "ERROR: Enter a positive number!";
else
calculateVariableCost();
cout << "The shipping cost is:£" << variableShippingCost << endl;
}
|