Translating two C++ functions to Pascal -
i can't seem understand why translation doesn't give desired result. here's c++ source code:
#include <stdio.h> int minint(int candidate = -1) { if (candidate - 1 >= 0) return candidate; (int stride = -1, stride2 = 2*stride; ; stride = stride2, stride2 += stride2) if (stride2 >= 0 || candidate + stride2 >= 0) return minint(candidate + stride); } int maxint(int candidate = 1) { if (candidate + 1 <= 0) return candidate; (int stride = 1, stride2 = 2*stride; ; stride = stride2, stride2 += stride2) if (stride2 <= 0 || candidate + stride2 <= 0) return maxint(candidate + stride); } int main() { (void) printf("max int %d\n", maxint()); (void) printf("min int %d\n", minint()); return 0; } it prints:
max int 2147483647 min int -2147483648 and here's pascal code (compiled using free pascal):
program translation; function minint (candidate : longint) : longint; var stride, stride2 : longint; var bool : boolean; begin bool := false; if (candidate - 1) >= 0 begin bool := true; minint := candidate; end; if (bool = false) begin stride := -1; stride2 := 2*stride; while (stride2 < 0) , (candidate + stride2 < 0) begin stride := stride2; stride2 += stride2; end; minint := minint(candidate + stride) end; end; function maxint (candidate : longint) : longint; var stride, stride2 : longint; var bool : boolean; begin bool := false; if (candidate + 1) <= 0 begin bool := true; maxint := candidate; end; if (bool = false) begin stride := 1; stride2 := 2*stride; while (stride2 > 0) , (candidate + stride2 > 0) begin stride := stride2; stride2 += stride2; end; maxint := minint(candidate + stride) end; end; begin writeln(maxint(1)); writeln(minint(-1)); end. which reason prints:
1073741825 2147483647 very, odd. 'maxint' value approximately half of needs be, , 'minint' value positive (actually, it's 'maxint' value supposed be).
what missing? bear in mind prohibited using sequencers (that is, commands such exit - hence boolean) , default arguments.
do not rely on underflow/overflow behaviour in c++. undefined.
instead, use limits library determine integer size limitations.
#include <iostream> #include <limits> int main() { std::cout << std::numeric_limits<int>::max() << '\n'; std::cout << std::numeric_limits<int>::min() << '\n'; return 0; } in pascal, longint has fixed size.
can rely on being 4 bytes long.
in regards pascal code, have typo in "maxint" function.
the line:
maxint := minint(candidate + stride) should be:
maxint := maxint(candidate + stride)
Comments
Post a Comment