0

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
1 Year
Discussion Span
Last Post by ddanbe
1

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

Votes + Comments
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.

Votes + Comments
explicit conversion and implicit conversion Those the terms i was looking for Thank you so much for your aide thank you
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.