I am trying to calculate p1 = (1/1) (1/2) ... * (1 / n), but something is wrong and printf gives me 0.000 ... 0
#include <stdio.h> int main(void) { int i,num; float p3; do { printf ("give number N>3 : \n" ); scanf( "%d", &num ); } while( num <= 3 ); i = 1; p3 = 1; do { p3=p3*(1/i); printf( "%f\n",p3 ); } while ( i <= num ); printf("\nP3=%f",p3); return 0; }
(1/i)
i is int , so this is integer division, resulting in 0 if i > 1 . Use 1.0/i to get floating point division.
i
int
i > 1
1.0/i
1 is an integer, i is an integer. Thus, 1/i will be an integer, i.e. the result will be truncated. To perform floating point division, one of the operands must be of type float (or, better, of type double ):
1
1/i
float
double
p3 *= 1. / i;
I had the same problem. The main case:
when you want to get a float output from two integers, you need to convert one to float
int c = 15; int b = 8; printf("result is float %f\n", c / (float) b); // result is float 1.875000 printf("result is float %f\n", (float) c / b); // result is float 1.875000
Source: https://habr.com/ru/post/1445325/More articles:Index error in python - pythonLaunch another application for the Windows store - windows-8Associating a Dictionary with WinRT ListBox - windows-runtimePadrino controller abstraction - ruby | fooobar.comAccurate Position D3 Chord Diagram - javascriptThe ASP.Net popup menu always returns the first value on a button click event - asp.netGrails form submit reasons 404 - grailsSerializing Azure Mobile Services objects - azureHow can I switch the string from "lastName, firstName" to "firstName LastName"? - stringhtaccess missing www - apacheAll Articles