Hi today i noticed that this program [below] wont print the correct value and it always print 0.00000

``````#include <stdio.h>
#include <stdlib.h>

int main()
{

float S;

int n;

scanf("%d" , &n);

S=1/n;
printf ("%f", S);

return 0;
``````

but when i asked my teacher he said you should make it like this

``````#include <stdio.h>
#include <stdlib.h>

int main()
{

float S;

int n;

scanf("%d" , &n);

S=(float)1/n;
printf ("%f", S);

return 0;
``````

but when i asked why you did that ? what's that technique? he didnt gave me a clear answer so please make me understand what happens

3
Contributors
2
Replies
18
Views
2 Years
Discussion Span
Last Post by ddanbe

For `S = 1/n`, as 1 and n are both integers you are performing integer division. Assume that n = 4, then the answer is equivalent to asking "How many times does 4 go into 1" - answer = zero times.

To solve this, you need to make the first operand in the equation a `float`.
Your teacher said to do that by casting `1` as type float - `(float)1`
You could also write 1 as a float - 1.0, therefore `S = 1.0/n`

Defining your n variable on line 10 as`float n;` or writing `s = 1 / 4.0;` would also do the trick.
`(float)1` is considered ugly, but needed in some cases. It is called explicit conversion.
An expression like `s = 1.0/n`where n is an integer is called implicit conversion.
The compiler figures out to implicitely convert the `n` to float and performs a float division.