02-15-06 12:57 PM
On 15 Feb 2006 04:00:56 -0800, ramanchalotra@gmail.com wrote:
> Deat All
>
> I have written a piece of code as
>
> #include<stdio.h>
>
> main()
> {
> float f;
> printf("\n Enter a float value ");
> scanf("%f",&f);
> printf("\n Value = %f\n ",f);
> }
>
> when i ran this code the output looks as
>
> Enter a float value 1234.678
> Value = 1234.677979
>
> Where i am making mistake ..
There are various `problems' with this program:
- The main function is incorrect. Sun Studio 10 reports:
"foo.c", line 5: warning: old-style declaration or incorrect type for: main
A similar message is displayed by GCC:
foo.c:5: warning: return type defaults to `int'
- You are not returning any status at all from main(), even though its
lack of a proper function declaration means it defaults to 'returning
an int'.
- Output to stdout may be line-buffered. This means that your prompt,
which doesn't end with a newline may never appear until a newline has
reached standard output. Your program will then happily block,
waiting for input in scanf(), but the user won't know anything about
the reason the program appears to do nothing at all. Not good.
You should definitely use something like:
printf("Enter a float value: ");
fflush(stdout);
- It's probably bad style to print a newline and then a space, as in:
printf("\n Foo");
This ends up showing as a very awkward space at the first column of my
terminal:
|keramida@beatrix:/home/keramida$ ./a.out
|
| Enter a float value: 123
|
| Value = 123.000000
|keramida@beatrix:/home/keramida$
Similarly, printing a newline right after scanf() has returned from a
line-buffered input call, results in a 'double newline', shown above
as an empty line between the two lines displayed by your printf()
calls.
- Most importantly, you are using 'float', which has limited precision.
It's not strange that you get a limited precision. Try this instead:
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int
5 main(void)
6 {
7 double f;
8
9 printf("Enter a float value: ");
10 fflush(stdout);
11
12 scanf("%lf", &f);
13
14 printf("Value = %lf\n", f);
15 return EXIT_SUCCESS;
16 }
This should work fine:
keramida@beatrix:/home/keramida$ cc -Xc foo.c -lm
keramida@beatrix:/home/keramida$ ./a.out
Enter a float value: 1234.678
Value = 1234.678000
keramida@beatrix:/home/keramida$
[ Post a follow-up to this message ]
|