So in C++ i can do something like:
DWORD count;
count = 3 / 1.699999;
cout << count;
which will result in:
1
Delphi however complains Cardinal and Extended mismatch.
var
count: DWORD;
begin
count := 3 / 1.6;
Writeln(inttostr(count));
So i either have to round count := round(3 / 1.6)
which results in:
2
or trunc count := trunc(3 / 1.6)
which results in
1
Is trunc really the way to go? Is there maybe a compiler switch i would have to toggle?
You would think it's easy to google something like that but trust me it isn't.
Thanks for your time!
C/C++ only has one arithmetic division operator - /
- but its behavior depends on the type of operands you pass to it. It can perform both integer division and floating point division .
Delphi has two arithmetic division operations - div
for integer division , and /
for floating point division .
Your C++ code is performing floating point division , and then assigning the result to a DWORD
, which is not a floating point type, so the assignment truncates off the decimal point:
1 / 1.699999
is 1.764706920415836
, which truncates to 1
.
In Delphi, the /
operator returns an Extended
, which is a floating-point type. Unlike C/C++, Delphi does not allow a floating-point type to be assigned directly to an integral type. You have to use Round()
or Trunc()
.
In this case, the Delphi equivalent of your C++ code is to use Trunc()
:
var
count: DWORD;
begin
count := Trunc(3 / 1.699999);
Write(IntToStr(count));
The easiest is to use trunc(3 /1.699999).
.
Another way is to use a previous multiplication before the division.
var
count: DWORD;
begin
count := 3;
count := (count*1000000) div 1699999;
Writeln(inttostr(count));
Of course, to avoid overflow, count
should be < maxInt div 1000000
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.