Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about float data type declaration in C++

Tags:

c++

c

a complete newbie here. For my school homework, I was given to write a program that displays -

s= 1 + 1/2 + 1/3 + 1/4 ..... + 1/n

Here's what I did -

#include<iostream.h>
#include<conio.h>

void main()
{
    clrscr();
    int a;
    float s=0, n;
    cin>>a;
    for(n=1;n<=a;n++)
    {
        s+=1/n;
    }
    cout<<s;
    getch();
}

It perfectly displays what it should. However, in the past I have only written programs which uses int data type. To my understanding, int data type does not contain any decimal place whereas float does. So I don't know much about float yet. Later that night, I was watching some video on YouTube in which he was writing the exact same program but in a little different way. The video was in some foreign language so I couldn't understand it. What he did was declared 'n' as an integer.

int a, n;
float s=0;

instead of

int a
float s=0, n;

But this was not displaying the desired result. So he went ahead and showed two ways to correct it. He made changes in the for loop body -

s+=1.0f/n;

and

s+=1/(float)n;

To my understanding, he declared 'n' a float data type later in the program(Am I right?). So, my question is, both display the same result but is there any difference between the two? As we are declaring 'n' a float, why he has written 1.0f instead of n.f or f.n. I tried it but it gives error. And in the second method, why we can't write 1(float)/n instead of 1/(float)n? As in the first method we have added float suffix with 1. Also, is there a difference between 1.f and 1.0f?

I tried to google my question but couldn't find any answer. Also, another confusion that came to my mind after a few hours is - Why are we even declaring 'n' a float? As per the program, the sum should come out as a real number. So, shouldn't we declare only 's' a float. The more I think the more I confuse my brain. Please help!

Thank You.

like image 911
Devansh Kumar Avatar asked Dec 11 '22 21:12

Devansh Kumar


1 Answers

The reason is that integer division behaves different than floating point division.

4 / 3 gives you the integer 1. 10 / 3 gives you the integer 3.

However, 4.0f / 3 gives you the float 1.3333..., 10.0f / 3 gives you the float 3.3333...

So if you have:

float f = 4 / 3;

4 / 3 will give you the integer 1, which will then be stored into the float f as 1.0f.

You instead have to make sure either the divisor or the dividend is a float:

float f = 4.0f / 3;
float f = 4 / 3.0f;

If you have two integer variables, then you have to convert one of them to a float first:

int a = ..., b = ...;
float f = (float)a / b;
float f = a / (float)b;

The first is equivalent to something like:

float tmp = a;
float f = tmp / b;
like image 199
Claudiu Avatar answered Dec 13 '22 11:12

Claudiu