C++ Primer Plus Chapter 2 Exercise 5

c plus plusExercise 5 requires us to do some more computations. Here is my solution:

5. Write a program that has main() call a user-defined function that takes a distance in
light years as an argument and then returns the distance in astronomical units. The program
should request the light year value as input from the user and display the result, as
shown in the following code:
Enter the number of light years: 4.2
4.2 light years = 265608 astronomical units.
An astronomical unit is the average distance from the earth to the sun (about
150,000,000 km or 93,000,000 miles), and a light year is the distance light travels in a
year (about 10 trillion kilometers or 6 trillion miles). (The nearest star after the sun is
about 4.2 light years away.) Use type double (as in Listing 2.4) and this conversion
factor:
1 light year = 63,240 astronomical units

 #include <iostream>

using namespace std;

double lightyears(double);
double years;

int main()
{
cout << "Enter number of light years: ";
cin >> years;

cout << years << " light years = " << lightyears(years) << " astronomical units" << endl;
cin.ignore();

return 0;
}

double lightyears(double years)
{
return (years * 63240);
}
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s