Page 1 of 1
How can I get different types output in C?
Posted: Wed Oct 24, 2012 11:19 am
by Nandika
Hello Friends,
I coded small program using C (with C Free 5)
Code: Select all
#include <stdio.h>
int main(){
float f;
f=5/2;
printf ("%f",f);
}
Print result is 2.000000
What is the error in my code?
I wished 2.5
I already found some about printf() command.according to this table.
- Conversion letters.
- table1.PNG (35.94 KiB) Viewed 12846 times
Cant I use this Conversion letters with variables?
Re: How can I get different types output in C?
Posted: Wed Oct 24, 2012 2:24 pm
by Nandika
ok Now I have a Solution ....
cording was modified as this,
Code: Select all
#include <stdio.h>
int main(){
float f;
f=5.0/2.0;
printf ("%f",f);
}
As I think,
My assumption is,
My opinion is,
if number is wrote as 5 compiler get it as an integer..therefore,output was integer.
if 5.0 compiler get it as a float...therefore output was float
.
Is My assumption correct?
Re: How can I get different types output in C?
Posted: Fri Oct 26, 2012 10:26 am
by Neo
No. It is not the compiler. Compiler has done a correct thing here.
Integers and Real (floating point) numbers are treated in this way by compilers.
When you divide 5/2, these are two integers you need to divide. So the result is an integer.
What you have to do here is to inform the compiler that you need a Real (floating-point) division rather than an integer division. To do that, it is enough to make one of the numbers to be Real such as 5.0/2 or 5/2.0. So compiler knows what you want.
Try this:
float a = 5;
float b = 2;
float c;
c = a / b;
You will see that 'c' returns 2.5 as expected. The reason is, since you used 'a' and 'b', the compiler knows you need a Real division.
Hope this is fully clear now.
Re: How can I get different types output in C?
Posted: Fri Oct 26, 2012 10:48 pm
by Nandika
Thank you Neo....
Now fully clear my problem .
This code also work well,
Code: Select all
#include<stdio.h>
int main(){
float a=5;
float b=2;
float c;
c=a/b;
printf("%f",c);
return(0);
}
Re: How can I get different types output in C?
Posted: Sat Oct 27, 2012 7:22 pm
by Herath
I am using it in the short form like the following,
Code: Select all
#include <stdio.h>
int main(){
float f;
f=5/2.0;
printf ("%f",f);
}
Note the "2.0".
. You could make either one of them as float.
-- Sorry it has already been answered. I did not read the whole thing except the codes.
Re: How can I get different types output in C?
Posted: Sat Oct 27, 2012 7:41 pm
by Neo
Nice to see our great Herath is also back in to business!!!!
Re: How can I get different types output in C?
Posted: Sat Oct 27, 2012 7:43 pm
by Herath
Been checking the forum, but haven't been involving much.
Hi
Re: How can I get different types output in C?
Posted: Wed Oct 31, 2012 2:57 pm
by Nandika
Thank you Herath for your reply...