-3

My code is not showing exact float value means number after point is not displayed by the code I am using Turbo C for sum up the series 1 + 1/3 + 1/5 + 1/7 + 1/9+….. Up to N terms

#include<iostream.h>
#include<conio.h>
void main()
{
    int k=0;
    int m=0;
    int s=1;
    clrscr();
    cout<<"Enter the limit of the series: ";
    cin>>m;
    for(int j=1;j<=m;j=j+2)
    {
          m=1/j;
          s+=m;
    }
    cout<<"Sum of the given series is: "<<s;
    getch();
}
user2241865
  • 113
  • 4
  • 14

4 Answers4

3

You're using int which only displays Integer (ie whole number) values. It truncates any decimal places because it assumes you don't want them. Try using float or double instead.

Eric Palace
  • 322
  • 2
  • 14
1

Integer division will not give you anything other than integer results.

You need to:

  1. Change s to a float or double.
  2. change m to a float or double.
  3. Change 1 in 1/j to 1.0f or 1.0 (for float and double respectively).

Now, you probably also want to use a different variable than m for your input and for-loop limit variable, so that you don't stop too quickly once the calculation starts.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

Use the type double for variables m and s.

shiraz
  • 1,208
  • 2
  • 12
  • 26
0

Here are the variables you declared in your code.

int k=0;
int m=0;
int s=1;

Where exactly do you think you have a floating point number?
(which would have to be of type float or double)

You do know that int means integer, right?
(eg. Not a floating point number)

abelenky
  • 63,815
  • 23
  • 109
  • 159