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

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

commented: thanks man :) +1

Defining your n variable on line 10 asfloat 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/nwhere n is an integer is called implicit conversion.
The compiler figures out to implicitely convert the n to float and performs a float division.

commented: explicit conversion and implicit conversion Those the terms i was looking for Thank you so much for your aide thank you +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.