C++ program to convert speed from miles/h to km/h using class

Learn, how can we convert speed from miles/h to km/h using the class and object approach?
Submitted by Shubh Pachori, on September 04, 2022

Example:

Input:
Enter Speed in miles/h :123.1

Output:
Speed in km/h : 198.11

C++ code to convert speed from miles/h to km/h using the class and object approach

#include <iostream>
using namespace std;

// create a class
class Speed {
  // private data member
 private:
  float miles_per_h;

  // public member functions
 public:
  // getSpeed() function to insert 
  // speed in miles/h
  void getSpeed() {
    cout << "Enter Speed in miles/h : ";
    cin >> miles_per_h;
  }

  // changeSpeed() function to convert speed
  // from miles/h to km/h
  double changeSpeed() {
    // initializing float type variable to
    // store speed in km/h
    float km_per_h;

    // converting the speed
    km_per_h = (miles_per_h / 0.6213712);

    // returning the speed
    return km_per_h;
  }
};

int main() {
  // create object
  Speed S;

  // float type variable to 
  // store converted speed
  float speed;

  // calling getSpeed() function to 
  // insert speed
  S.getSpeed();

  // calling changeSpeed() function 
  // to convert speed
  speed = S.changeSpeed();

  cout << "Speed in km/h : " << speed;

  return 0;
}

Output:

Enter Speed in miles/h : 222.231
Speed in km/h : 357.646

Explanation:

In the above code, we have created a class Speed, one float type data member miles_per_h to store the speed in miles/h, and public member functions getSpeed() and changeSpeed() to store speed in miles/h and to convert it to km/h.

In the main() function, we are creating an object S of class Speed, reading the inputted speed by the user using getSpeed() function, and finally calling the changeSpeed() member function to convert it to km/h. The changeSpeed() function contains the logic to convert the speed from miles/h to km/h and printing the result.

C++ Class and Object Programs (Set 2) »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.