Wednesday 28 November 2012

Prgram to convert CM to Inches in C++

Purpose of Program


This program converts CM to inches.

Program



#include 

using namespace std;

// a program that converts cm to inches

int main()
{
    // we declare a numerical constant.
    const float cstCentPerInch = 2.54;

    // declare a floating point number.
    float cm, inches;

    //Enter the length
    cout << "Enter a length in cm: ";
    cin >> cm;

    //return the number of inches.
    inches = cm / cstCentPerInch; // this is a divison

    cout << endl << cm << " cm equals " << inches << " inches " << endl;

    return 0;
}

What are Reals / floating point numbers?

There are two main types of numbers. These are integers and floating point.

We've already come across integers (int) which are numbers like 1,2, -7.

Floating point numbers are numbers with decimals, like 1.2, 3.2, 1.1. In the above program we come across them when we declare the constant. Both the constant cstCentPerInch and 2.54 are floating point numbers.

We also enter a length as a floating point, and the result of the calculation is a floating point.

Division

In the above program we do a divison:

inches = cm / cstCentPerInch;

The result of that division is a floating point number, which we then output. There are many other mathematical operators we can use. In the above code we do a calculation ( cm / cstCentPerInch )  and then assign the result to a variable inches.

Purpose of Return statement in Main

When you finish a program the operating system can be interested in whether it finished successfully. Return 0 tells the operating system that you have completed the program without any errors.

No comments:

Post a Comment