Something or Nothing

Tuesday, March 24, 2009

I take my programming perfectionism too far, but I love it. I'm taking up C++ again and using the pretty good "C++ Primer Plus Fifth Edition" by Stephen Prata as a guide. I'm only in chapter two and "only know how" to do functions, assign variables, and do basic IO. I remember enough to do loops and if then else from when I did C++ in high school though. It means little projects get a little more advanced, like the clock project:

// time.cpp -- display current time using a separate function

#include <iostream>
using std::cout;
void clock(int, int);

int main()
{
using std::cin;
cout << "Enter the number of hours: ";
int hours;
cin >> hours;
cout << "Enter the number of minutes: ";
int minutes;
cin >> minutes;
clock(hours, minutes);

return 0;
}

void clock(int hours, int minutes)
{
using std::endl;
cout << "Time: " << hours << ":";
if ( minutes <= 9 )
{
cout << "0";
};

cout << minutes << endl;

return;
}


The example didn't have you take into account the output if a number was less than 10, which would normally display something like 1:9, which doesn't look as good. So with an if it becomes 1:09.

I find this to be a lot of fun, it's the first time I've gotten into separate functions and returning values. My High School C++ class just had us doing things in main.

Another:

// distance.cpp -- Convert light years to AU

#include <iostream>
double work(double);

int main()
{
using std::cout;
using std::cin;
using std::endl;

cout << "Enter the number of light years: ";
double l_years;
cin >> l_years;
double au = work(l_years);
cout << l_years << " light years = " << au << " astronomical units." <<
endl;

return 0;
}

double work(double distance)
{
distance = distance * 63240;

return distance;
}

0 Comments:

Post a Comment

<< Home