C programming - How to print numbers with a decimal component using only loops?

Posted by californiagrown on Stack Overflow See other posts from Stack Overflow or by californiagrown
Published on 2012-04-15T22:28:51Z Indexed on 2012/04/15 23:28 UTC
Read the original article Hit count: 177

Filed under:
|
|

I'm currently taking a basic intro to C programming class, and for our current assignment I am to write a program to convert the number of kilometers to miles using loops--no if-else, switch statements, or any other construct we haven't learned yet are allowed. So basically we can only use loops and some operators. The program will generate three identical tables (starting from 1 kilometer through the input value) for one number input using the while loop for the first set of calculations, the for loop for the second, and the do loop for the third.

I've written the entire program, however I'm having a bit of a problem with getting it to recognize an input with a decimal component.

Here is what I have for the while loop conversions:

#include <stdio.h>
#define KM_TO_MILE .62 

main (void)
{
 double km, mi, count;                                                          

 printf ("This program converts kilometers to miles.\n");

        do                                                                      
        {
               printf ("\nEnter a positive non-zero number");                   
               printf (" of kilometers of the race:  ");
               scanf  ("%lf", &km);                                             
               getchar();                                                      
        }while (km <= 1);                                                       


   printf ("\n KILOMETERS       MILES    (while loop)\n");                      
   printf (" ==========       =====\n");

        count = 1;                                                              
        while (count <= km)                                                     
        {                                                                       
              mi = KM_TO_MILE * count;                                          
              printf ("%8.3lf %14.3lf\n", count, mi);                  
              ++count;                                                                           
        }
        getchar();
}

The code reads in and converts integers fine, but because the increment only increases by 1 it won't print a number with a decimal component (e.g. 3.2, 22.6, etc.). Can someone point me in the right direction on this? I'd really appreciate any help! :)

© Stack Overflow or respective owner

Related posts about c

    Related posts about homework