|
-
Dec 26th, 2001, 06:34 AM
#1
Thread Starter
Hyperactive Member
Caught in a loop for some reason...
Hi, i am new to C and when i tested my little program there comes an infinite loooooop. I searched for bugs but couldn't find any, pls help out. Source code is here:
----------------------------------------------------------------------------
/* Calculates total earnings of salesman per week. */
#include <stdio.h>
int main()
{
float sales, commission;
int retainer = 200;
printf( "Enter sales in dollars (-1 to end): " );
scanf( "%.2f", &sales );
while ( sales != -1 ) {
commission = sales * 9 / 100;
printf( "\nSalary is: %.2f\n", commission + retainer );
printf( "Enter sales in dollars (-1 to end): " );
scanf( "%.2f", &sales );
}
return 0;
}
-----------------------------------------------------------------------------
The output of the program on my screen is attached in a .jpg file. Pls read and thnx in advance. Just pls find out whats wrong with this piece of code.
Last edited by iflash; Dec 26th, 2001 at 08:27 AM.
-
Dec 26th, 2001, 10:24 AM
#2
This works:
Code:
#include <stdio.h>
int main()
{
float sales, commission;
int retainer = 200;
printf( "Enter sales in dollars (-1 to end): " );
scanf( "%f", &sales );
while ( sales != -1 ) {
commission = sales * 9 / 100;
printf( "\nSalary is: %.2f\n", commission + retainer );
printf( "Enter sales in dollars (-1 to end): " );
scanf( "%f", &sales );
}
return 0;
}
-
Dec 26th, 2001, 10:40 AM
#3
Thread Starter
Hyperactive Member
hi thnx!
I tested your solution and it worked! BUt i still don't know where went wrong, the two pieces of code were exactly the same except the % 'point 2 f ' part. Is that it?
Any further explantion (brief) will be greatly appreciated!
thnx a lot jm
-
Dec 26th, 2001, 11:08 AM
#4
The %.2f format doesn't allow input. .2 means NO number in front of the decimal, ie. only numbers from .00 -> .99
You probably want something like "%f" or "%8.2f"
scanf formats DO NOT all work exactly like their printf cousins.
It can be a source of confusion. scanf can be a royal PITA.
By the way, you are much better off always getting strings from users. gets is okay for this.
Then you can test to see if they entered a number. Otherwise, scanf may create garbage if the user were to enter "T" instead of 9. Some compilers generate fatal errors for this kind of thing.
You don't want your program to abend on a user who is talking on the phone and entering data at the same time.
-
Dec 26th, 2001, 11:17 PM
#5
Thread Starter
Hyperactive Member
yep thnx
anyway i am still up to chapter 4 in my book lol.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|