Help with C, loops

I have to write a program that calculates simple interest. Then loops and does it again unless you input "-1". It works fine, but it should stop as soon as you input "-1", and it keeps going until the the end of the program.



#include


/* function main begins program execution */
int main( void )
{
float principal; /* define principal variable */
float itr; /* define interest variable */
int tm; /* define term in days variable */
float rtch; /* define interest charge variable */

while ( principal != -1 ){
/* input info */
printf( "Enter loan principal (-1 to end): " );
scanf_s( "%f", &principal );
printf( "Enter interest rate:" );
scanf_s( "%f", &itr );
printf( "Enter term of the loan in days: " );
scanf_s( "%d", &tm );


/* calculate */
rtch = (principal * itr * tm) /365;
printf( "The interest charge is $%.2f


", rtch );}


return 0;

} /* end */

BANG HEAD ON DESK

Comments

  • Seems to work fine, except a few problems:

    - You are using some non-standard scanf, it isn't clear whether this flushes the input buffer properly or not. Had it been standard scanf(), you would have to write a getchar() after each call, to remove the line feed character that is put into stdin when the user presses enter.

    - You are using int, you should use signed int. It is implementation-defined whether "int" is signed or not, it depends on the compiler.
  • [code]#include

    [color=Red]#include [/color]
    /* function main begins program execution */
    int main( void )
    {
    float principal; /* define principal variable */
    float itr; /* define interest variable */
    int tm; /* define term in days variable */
    float rtch; /* define interest charge variable */

    while ( principal != -1 ){
    /* input info */
    printf( "Enter loan principal (-1 to end): " );
    scanf_s( "%f", &principal );
    [color=Red]if(principal==-1)
    {
    exit(0);
    }[/color]
    printf( "Enter interest rate:" );
    scanf_s( "%f", &itr );
    printf( "Enter term of the loan in days: " );
    scanf_s( "%d", &tm );


    /* calculate */
    rtch = (principal * itr * tm) /365;
    printf( "The interest charge is $%.2f


    ", rtch );}


    return 0;

    } /* end */[/code]


    That should solve your problem.

    But then I am just a toddler in C/C++.
  • There is no header called process.h in the C language.

    exit() is found in stdlib.h
  • You are right about exit() being found in stdlib.h. Unfortunately, Turbo C++ does have it and there you have the choice of either stdlib or process.h. I blundered and put process.h instead of stdlib.h.

    Many thanks for pointing that out.
  • This post was posted twice. Wonder how and why.
  • Post deleted for the reason given in my second post.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories