Đumić Branislav - 1 year ago 276

Pascal Question

I have wrote functions in C++ and Pascal that give me n-th Fibbonacci number. As expected for large n-values(n>92,because even f(93) > 2^63+1) I was getting incorrect results.

But when I compared them for same n I would get same result in both languages.

This was opposed to my idea that I would get some random number.

I am wondering why I am getting same results and why I didn't get integer overflow in the first place.

Could somebody explain this to me?

Code:

`#include <iostream>`

#include <cmath>

#include <iomanip>

using namespace std;

long long fibo(int n){

long long a1,a2,pom;

int i=1;

a1 = 0; a2 = 1;

while(i<=n){

pom = a2;

a2 = a1 + a2;

a1 = pom;

i++;

}

return a1;

}

int main(){

int n;

cin >> n;

cout << "Function: "<< setprecision(50) << fibo(n) << endl;

}

`Program AddNums(output);`

function fibo(n:integer):int64;

var

a1,a2,pom:int64;

i:integer;

begin

a1:=0;a2:=1;i:=1;

while(i<=n)do

begin

pom:= a2;

a2:= a1 + a2;

a1:= pom;

inc(i);

end;

fibo:=a1;

end;

var

n:integer;

begin

readln(n);

writeln(fibo(n));

end.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

A result that is *undefined* is not necessarily *random*. When you perform the same computation on the same platform using the same initial condition, you will arrive at the same result, even if it is incorrect.

In your case Pascal and C++ programs use the same underlying hardware with the same representation of `int64`

and `long long`

, and they instruct that hardware to perform the same sequence of mathematical operations on numbers that start off the same. Hence, they do arrive at the same number, representing the end result of this sequence of operations.

The result is still undefined, because if you run the same computation on a different platform, or even on the same platform but with different compiler settings, you may get an entirely different incorrect result.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**