1

Two similar codes, when they are run on two different computers, give two right answers, but they look different. How could it be explained? The aim is to calculate A+B.

Input: 1000000000 1000000000

Output-1: 2000000000

Output-2: 2e+009

#include <iostream>
#include <fstream>
using namespace std;
int main(){
  ifstream cin("input.txt");
  ofstream cout("output.txt");
  int a, b;
  cin >> a >> b;
  cout << a + b;
  return 0;
}
Peter Petrik
  • 9,701
  • 5
  • 41
  • 65
  • 13
    Tangent: calling your stream variables `cin` and `cout` is insane... – Oliver Charlesworth Aug 22 '14 at 08:04
  • 2
    @OliCharlesworth and when you add that to `using namespace std` .... – quantdev Aug 22 '14 at 08:04
  • What compiler/platform are you using to generate output #2? – Oliver Charlesworth Aug 22 '14 at 08:06
  • 1
    @quantdev I think that's in fact the goal : you can redirect `cin`/`cout` by shadowing them, or not. – Quentin Aug 22 '14 at 08:07
  • Are you compiling your code on each machine or do you use the same executable? – Gio Aug 22 '14 at 08:07
  • 1
    On what system (compiler and OS with versions please) is the output 2e+009? That looks like a floating point representation, which shouldn't happen for the program you've listed with `int` types for `a` and `b`. Are you sure that output's not for an old version of the program where you used `double` or `float`? – Tony Delroy Aug 22 '14 at 08:09
  • @Quentin well peut-etre, I don't know who would teach that, that's a terrible idea. – quantdev Aug 22 '14 at 08:09
  • No, actually both codes were run on Windows 7 Ultimate and we are sure that these outputs are for listed code. – Alexander Dimov Aug 22 '14 at 08:17
  • 2
    Then I think it must be caused by differences in locale-specific facets... I don't know much about the details, but suggest you read up - [this](http://www.math.hkbu.edu.hk/parallel/pgi/doc/pgC++_lib/stdlibug/sta_9169.htm) seems like a reasonable starting point. – Tony Delroy Aug 22 '14 at 08:25
  • @TonyD Thank you for your reasonable answers! – Alexander Dimov Aug 22 '14 at 08:29
  • I do not think locale can influence if a number is written in scientific notation or not. You have the executable compiled on one machine and run on both of them? Or you compiled (different) executable on each machine? – Peter Petrik Aug 22 '14 at 08:50
  • possible duplicate of [How to find mantissa length on a particular machine?](http://stackoverflow.com/questions/502022/how-to-find-mantissa-length-on-a-particular-machine) – Klaus Aug 22 '14 at 09:08
  • @OliCharlesworth Besides that it might be bad practice I dont see any technical problem with it. The declarations will successfully hide `std::cout` and `std::cin` and if you want to explicitely use those two streams all you have to do is to use them prefixed with their namespace. – Sebastian Hoffmann Aug 22 '14 at 10:09

0 Answers0