Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

passing float

Status
Not open for further replies.

bobetko

Programmer
Jan 14, 2003
155
0
0
US
Will somebody please tell why this doesn't work.... I am passing param by value:
Code:
float x = myfun();
printf("value = %.1f", x);

.........


float myfun(){
    float c = 0.5;
    return (c);
}

I am getting big numbers, something like 803459439.0 etc....
What's going on here? Can I pass float type number by value?

I also tried this printf("value = %.1f", 5); and I got very big number.... several lines of numbers.... Why?

Thanks in advance....
 
I also tried this printf("value = %.1f", 5); and I got very big number.... several lines of numbers.... Why?
Because 5 is an int. Try this.
Code:
printf("value = %.1f", 5[blue].0F[/blue]);
 
> What's going on here? Can I pass float type number by value?
First guess would be you didn't prototype your function.
Some compilers don't check too well, and as written the compiler might assume your function returns int. Post complete programs next time, we can't tell what you've really done.

> printf("value = %.1f\n", 5);
[tt]$ gcc -W -Wall -ansi -pedantic foo.c
foo.c: In function ‘main’:
foo.c:9: warning: format ‘%.1f’ expects type ‘double’, but argument 2 has type ‘int’
[/tt]
From my compiler.

--
 
There are 2 different moments here.
1. If no prototype before myfunc() call (see Salem's post), int myfunc() assumed then int-to-float promotion executed in the assignment stmt then float-to-double promotion executed in printf arg list. Of course, the results of these conversions are wrong.
2. printf("value = %.1f", 5); is wrong because of only float-to-double promotion (always!) executed in int printf(const char*,...) arg list, int arg passed as is but format specification wants double then treated int as double.
Moral:
1. Avoid func calls w/o prototypes.
2. Avoid using float type, always use double.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top