Computer Science Canada

Loop Help Needed

Author:  JWHooper [ Mon Feb 18, 2008 9:58 pm ]
Post subject:  Loop Help Needed

Write a program that displays the following table (note that 1 mile is 1.609 kilometers):

code:

Miles           Kilometers
1               1.609
2               3.218
...
9               14.481
10              16.09



.

.

.


I tried my own code for this:

code:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
        cout << "Miles" << setw(17) << "Kilometers\n\n";

        for (int mi = 1; mi <= 10; mi += 1)
        {
                double km = mi * 1.609;
               
                cout << left;
                cout << mi << setw(16) << km << endl;
        }


        return 0;
}

But, the result was:

code:

Miles        Kilometers
11.609
23.218
...
914.481
1016.09


Can anyone revise and edit my code in terms of basic C++ language terms (not advanced or anything)? If anyone can, I would be appreciated.


Thanks,

J.

Author:  Nick [ Mon Feb 18, 2008 10:05 pm ]
Post subject:  RE:Loop Help Needed

I haven't tried it but it should work
code:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
   cout << "Miles" << setw(17) << "Kilometers\n\n";

   for (int mi = 1; mi <= 10; mi += 1)
   {
      double km = mi * 1.609;
     
      cout << left;
      cout << mi << "             " << km << endl;
   }


   return 0;
}

Author:  JWHooper [ Mon Feb 18, 2008 10:18 pm ]
Post subject:  Re: RE:Loop Help Needed

momop @ Mon Feb 18, 2008 7:05 pm wrote:
I haven't tried it but it should work
code:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
   cout << "Miles" << setw(17) << "Kilometers\n\n";

   for (int mi = 1; mi <= 10; mi += 1)
   {
      double km = mi * 1.609;
     
      cout << left;
      cout << mi << "             " << km << endl;
   }


   return 0;
}


Okay. I'll try this on my compiler a little later.

Author:  Nick [ Mon Feb 18, 2008 10:24 pm ]
Post subject:  RE:Loop Help Needed

Posted Image, might have been reduced in size. Click Image to view fullscreen.

this what you wanted?

Author:  wtd [ Tue Feb 19, 2008 11:17 am ]
Post subject:  RE:Loop Help Needed

You should set the width for the first "column" to 2 to get proepr alignment.

Author:  JWHooper [ Tue Feb 19, 2008 9:37 pm ]
Post subject:  Re: RE:Loop Help Needed

momop @ Mon Feb 18, 2008 7:24 pm wrote:
Posted Image, might have been reduced in size. Click Image to view fullscreen.

this what you wanted?


Almost, but I wanted to make the 10 miles column look perfect, too.

Author:  md [ Tue Feb 19, 2008 9:50 pm ]
Post subject:  RE:Loop Help Needed

setw aligns to the left, use it on the first column instead of teh second. Problem solved!


: