Confusion about declaring a float data type in C ++

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

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

Here is 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 you need. However, in the past I only had written programs that use the int data type. In my opinion, the int data type does not contain a decimal place, whereas float does. So I don’t know much about swimming yet. Later that night, I watched a video on YouTube in which he wrote the same program, but in a slightly different way. The video was in some foreign language, so I could not understand it. What he did was declared as an "integer".

int a, n;
float s=0;

instead

int a
float s=0, n;

. . -

s+=1.0f/n;

s+=1/(float)n;

, 'n' ( ?). , : , ? "n" float, 1.0f n.f f.n. , . 1 (float)/n 1/(float) n? , float 1. , 1.f 1.0f?

, . , , - "n" ? . 's' float. , . , !

.

+4
5

n , int. , , :

s+=1/n;

, , , . , 1/2 0, 1 2 0,5, 0.

, . C , .

:

s += (float)1/n

:

s += 1/(float)n

1 , :

s += 1.0/n

f:

s += 1.0f/n

f ( U, L LL) , .

+3

, .

4 / 3 1. 10 / 3 3.

4.0f / 3 float 1.3333..., 10.0f / 3 float 3.3333...

, :

float f = 4 / 3;

4 / 3 1, float f 1.0f.

, , - float:

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

, float:

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

:

float tmp = a;
float f = tmp / b;
+7

, , . , . n . integer double ( ), c/++ , , . , , ..

(float) n
+1

'n' ( ?)

, ( , ) n an int, () float. .

, ?

. . int float, , , , float. . , , , . , , .

1.0f n.f f.n. , . [...] , 1.f 1.0f?

, . , .f. , 5 int, 5.0f 5.f - float; , 0 s. n.f , n (), .

, 1 (float)/n 1/(float) n?

(float)n - C- int n, 1(float) - .

+1

s+=1.0f/n;

s+=1/(float)n;

... , : , ?

.

C ++, , "" . , signed unsigned, signed "" unsigned. float double, float double.

, - 1/2 0, 0.5. , .

1.0f/n 1.0f float 1 n "" int, float,

1/(float) n n float, 1 int float.

Nitpicks:

  • void main() main, int main(). - ++:
    3.6.1
    ...
    2 main. . int, ...
  • Secondly, format your code - this makes reading and debugging easier for others. Spaces and indents are your friends - use them.


1. A constant expression 1.0without a suffix is ​​of type double. The suffix ftells the compiler to treat it like that float. 1.0/nwill result in a type value double.
+1
source

Source: https://habr.com/ru/post/1608075/


All Articles