1

I have written a simple program, that reads one integer number and prints: 1 / number.

I do not understand why the output is always: 0.000.

void main()
{
    int n = 0;
    scanf("%d",&n);

    float f = 1 / n;
    printf("%f",f);
}
oo_miguel
  • 2,314
  • 15
  • 28
amir
  • 2,224
  • 3
  • 21
  • 47

5 Answers5

6

Your (1/n) returns an integer value!

You need to have at least one float value in division!

Change (1 / n) to (1.0 / n).

Ziezi
  • 6,187
  • 3
  • 36
  • 46
Rahul Jha
  • 1,111
  • 1
  • 10
  • 23
4

Try:

f = 1.0 / n;

The 1/n will be int that converted to float and assigned to f.

int value of 1 / n is 0 for all n > 1.

1.0 / n will perform the calculation in float and f will be assigned the expected result.

Roman Pustylnikov
  • 1,917
  • 1
  • 9
  • 18
2

The reason for your problem is, that both of your paramaters are integers. Dividing them will always yield an integer.

Try something like:

int n;
scanf("%d",&n);
float f=1.0f/n;      // n will be converted to type: float

OR alternatively to read in a float.

float n;
scanf("%f",&n);
float f=1/n;         // 1 will be converted to type: float
oo_miguel
  • 2,314
  • 15
  • 28
0

Please try this, it works

#include <stdio.h>
#include <conio.h>

 void main(  )
{
  float f = 0.0;
  float n = 0.0;
  scanf( "%f", &n );
  f = 1.0 / n;
  printf( "    %5.5f     ", f );
  getch(  );
}
BobRun
  • 758
  • 5
  • 12
0

Or perhaps you should just "cast" the operation like this

float f = (float)1 / n; This will work!!!

Sigmabooma
  • 23
  • 7