Friday, July 31, 2009

Help fixing a C program that I'm working on...?

for some reason i keep getting 1245036 as the new credit limit, no matter what I put in. Help?











#include %26lt;stdio.h%26gt;








int main()


{





int employee = 1;


int accountNumber;


int creditBefore;


int currentBalance;


int creditAfter;





while ( employee %26lt;= 3 ){








printf( "Enter account number: ");


scanf( "%d", %26amp;accountNumber );





printf( "Enter current balance: ");


scanf( "%d", %26amp;currentBalance );





printf( "Enter current credit limit: ");


scanf( "%d", %26amp;creditBefore );





creditAfter = creditBefore / 2;





printf( "Your new credit limit is %d\n", %26amp;creditAfter );





if ( creditAfter %26lt; currentBalance ){


printf( "Current balance exceeds new credit limit.\n" );


}


else{


printf( "Current balance does not exceed new credit limit.\n" );


}





}





return 0;





}

Help fixing a C program that I'm working on...?
It's been a while since I coded in C, but here goes:





In the printf("Your new credit limit is %d\n", %26amp;creditAfter); statement, the %26amp; indicates that you want to print the ADDRESS of creditAfter, not the value. Try it without the %26amp;.





I'm assuming that you're just playing around here. So the following two points aren't related to the problem that you're having but may yield unintended results.





If you divide an odd numbered integer by 2, the result will be a real number. By declaring creditAfter as int, any decimal portion will be truncated.





The condition for your while loop checks that employee is less than 3; however, employee is not being incremented within the loop. This will result in an infinite loop.
Reply:This line


printf( "Your new credit limit is %d\n", %26amp;creditAfter );


must be in the form


printf( "Your new credit limit is %d\n", creditAfter );





Here is the complete better program:





#include %26lt;stdio.h%26gt;





int main()


{


int employee = 1;


int accountNumber;


int creditBefore;


int currentBalance;


int creditAfter;





while ( employee %26lt;= 3 ){








printf( "\n\n\nEnter account number: ");


scanf( "%d", %26amp;accountNumber );





printf( "\nEnter current balance: ");


scanf( "%d", %26amp;currentBalance );





printf( "\nEnter current credit limit: ");


scanf( "%d", %26amp;creditBefore );





creditAfter = creditBefore / 2;





printf( "\nYour new credit limit is %d\n", creditAfter );





if ( creditAfter %26lt; currentBalance ){


printf( "\nCurrent balance exceeds new credit limit.\n" );


}


else{


printf( "\nCurrent balance does not exceed new credit limit.\n" );


}





}





return 0;





}
Reply:the statement scanf( "%d", ¤tBalance ); has to use %26amp;currentBalance, this particular variable is not declared, also the symbol should be %26amp; to mention the address


No comments:

Post a Comment