0
#include <iostream> 
#include <cmath>

double buf[128 * 1024];
int main()
{
    int i = 0;
    unsigned long long n; // 64-bit unsigned integer
    while (std::cin>>n) {
        buf[i ++] = double(sqrt(n)); // store in buffer
    }
    i--;
    while(i>=0){
        printf("%lf\n",buf[i]); // When i am using this it works fine.
        //std::cout<<buf[i]<<std::endl; // When i am using this line instead of printf function it shows wrong answer. why?
        i--;
}


    return 0;
}

I have compiled it with G++. While I am trying to print the output with printf funtion then it is accepted. But when I am using cout function then it gives wrong answer. Why is it happened? This code shows compilation error when i am compiling it in GCC7.1 . What is the reason of this? Problem Link : https://acm.timus.ru/problem.aspx?space=1&num=1001

Sujan
  • 7
  • 1
  • 6
  • Surprisingly, your question doesn't actually contain a question. Edit it to spell the problem in title. – Tanveer Badar Apr 04 '20 at 22:52
  • While I am trying to print the output with printf funtion then it is accepted. But when I am using cout function then it gives wrong answer. why is it happened? – Sujan Apr 04 '20 at 22:55
  • Do you have an example input that fails the test? So we can see what the two outputs are, and work out how to make them the same. – Rup Apr 04 '20 at 22:57
  • I have written all the code above. In my pc compiler both are working. – Sujan Apr 04 '20 at 23:04

1 Answers1

2

Using the << operator with std::cout rounds to 6 significant figures by default and uses scientific notation for large floating point numbers. To disable the scientific notation, include the <iomanip> header and use std::cout << std::fixed << buf[i];. Using std::fixed will also set the rounding to 6 digits after the decimal point.

eesiraed
  • 4,626
  • 4
  • 16
  • 34
  • but why printf function is working without fixing the floating number? – Sujan Apr 04 '20 at 23:00
  • @Sujan This behavior is specific to the C++ I/O streams. `printf` by default doesn't use scientific notation and rounds to 6 digits after the decimal point. – eesiraed Apr 04 '20 at 23:01
  • @Sujan The rounding is done during the output operation, not during the calculations. – eesiraed Apr 04 '20 at 23:09
  • ok thanks. but the fact is not clear to me. Is there any tutorial on it? – Sujan Apr 04 '20 at 23:09
  • Let me know if there is any details discussion on it. Thanks in advance. – Sujan Apr 04 '20 at 23:12
  • @Sujan Online tutorials for C++ generally aren't great, but a [good book](https://stackoverflow.com/q/388242/9254539) might cover this stuff. There are detailed reference pages available online such as [this](https://en.cppreference.com/w/cpp/locale/num_put/put) but the C++ rules are complicated and they are pretty hard to read for beginners. – eesiraed Apr 04 '20 at 23:20