In: Computer Science
Intro C++ Programming Chapter 6 Functions
You have been tasked to write a new program for the Research Center's shipping department. The shipping charges for the center are as follows:
Weight of Package (in
kilograms)
Rate per mile Shipped
2 kg or
less
$0.05
Over 2 kg but no more than 6 kg $0.09
Over 6 kg but not more than 10 kg $0.12
Over 10 kg $0.20
Write a function in a program that asks for the weight of a package in kilograms and the distance it is to be shipped. Using that data, write another function that calculates the shipping charge and returns it to the main program and displays the value there.
For the second function, pass the two values (weight and distance) into the function as arguments. In the function if the shipping distance the user provided earlier is a distance greater than 200 miles, there will be an additional charge of $25 added to the order. For example, if an item weighing 20 kg is shipped 250 miles, the total cost will be $75, calculated by the formula: ((250 miles * 0.20) + 25).
input validation: Do not accept any weights less than 0.5 kilograms, nor any distances less than 0 miles.
#include <iostream>
#include<stdlib.h>
using namespace std;
int shipping_charge(float weight ,int distance){
//second function to calculate the shipping charge
int additional_charge=0;
float rate_per_mile,result;
if(weight<=2){
//if weight of package in kg is 2kg or
less
rate_per_mile=0.05;
}
else if(weight>2 &&
weight<=6){ //if weight of package in kg over 2kg
but no more than 6kg
rate_per_mile=0.09;
}
else if(weight>6 && weight<=10){ //if
weight of package in kg over 6kg but no more than 10kg
rate_per_mile=0.12;
}
else if(weight>10){ //if weight of
package over 10kg
rate_per_mile=0.20;
}
if(distance>200){ //if distance is
greater than 200 update additional_charge=25
additional_charge=25;
}
result=(distance*rate_per_mile)+additional_charge;
return result; //return
the result to the main function
}
int main(){ //main function that
asks for the weight of a package in kilograms and the distance in
miles it is to be shipped
int distance;
float weight,output;
cout<< "Enter Weight of Package in Kilograms:
";
cin>> weight;
if(weight<=0.5){ //displaying instant
error message to enter valid data and exiting from the
program
cout<< "Enter Weights greater
than 0.5 Km" <<endl;
exit(0); //must
include<stdlib.h>
}
cout<< "Enter distance to be Shipped: ";
cin>> distance;
if(distance<=0){ //displaying instant error message
to enter valid data and exiting from the program
cout<< "Enter Distance
greater than 0 miles" <<endl;
exit(0); //must
include<stdlib.h>
}
output=shipping_charge(weight,distance);
//storing returned value from second function in the
output
cout<< "Total Cost:
$"<<output<<endl; //displaying the total
cost
}
Output: //Hope it helps.If you have any doubts feel free to add comments.