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);
}
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.
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
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( );
}
Or perhaps you should just "cast" the operation like this
float f = (float)1 / n; This will work!!!