How does the cout expression affect the O / P of the written code?

#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;

int main() {
    int t;
    double n;
    cin>>t;
    while(t--)
    {
        cin>>n;
        double x;
        for(int i=1;i<=10000;i++)
        {
            x=n*i;
            if(x==ceilf(x))
            {
                cout<<i<<endl;
                break;
            }
        }
    }
    return 0;
}

For I / P:

3
5
2.98
3.16

O / P:

1

If my code is:

#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;

int main() {
    int t;
    double n;
    cin>>t;
    while(t--)
    {
        cin>>n;
        double x;
        for(int i=1;i<=10000;i++)
        {
            x=n*i;
            cout<<"";//only this statement is added;
            if(x==ceilf(x))
            {
                cout<<i<<endl;
                break;
            }
        }
    }
    return 0;
}

For the same O / P input:

1
fifty
25

The only extra line added in the second code: cout<<"";

Can someone help with the search, why is there such a difference in the output just because of the cout instruction added in the 2nd code?

+4
source share
4 answers

Well, this is the real Heisenbug . I tried to reduce the code to a minimal duplicate example and got this ( http://ideone.com/mFgs0S ):

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    float n;
    cin >> n;  // this input is needed to reproduce, but the value doesn't matter
    n = 2.98;  // overwrite the input value
    cout << "";  // comment this out => y = z = 149
    float x = n * 50;   // 149
    float y = ceilf(x); // 150
    cout << "";  // comment this out => y = z = 150
    float z = ceilf(x); // 149
    cout << "x:" << x << " y:" << y << " z:" << z << endl;
}

ceilf, -, iostream, . , , , , - , . , , gcc-4.9.2 gcc-5.1. ( ideone, gcc-4.3.2.)

+4

" . , 0,2, , , . , . , , , , .

, , : if (result == expectedResult)

, . , , , - , . "

http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm

, .

if(x==ceilf(x))

ceilf() float x, double. , .

x float ,

+2

, , , . , 50, , , - 50.00000000001. , double float s.

( Epsilon, , " " )

const double EPSILON = 0.000000001;

if (x==ceilf(x))

-

double difference = fabs(x - ceilf(x));
if (difference < EPSILON)

.

+2

-.
g++ (4.9.2-10) (3 ) - geeksforgeeks.org. , .
, , , - "++ (gcc)" . geeksforgeeks.org, "++", g++ ( Linux).
, , gcc ++ , .:)

0

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


All Articles