简体   繁体   English

DWORD部门Delphi / C ++

[英]DWORD division Delphi / C++

So in C++ i can do something like: 因此,在C ++中,我可以执行以下操作:

DWORD count;

count = 3 / 1.699999;

cout << count;

which will result in: 这将导致:

1 1个

Delphi however complains Cardinal and Extended mismatch. 但是,Delphi抱怨Cardinal和Extended不匹配。

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: 所以我要么必须四舍五入count := round(3 / 1.6)这导致:

2 2

or trunc count := trunc(3 / 1.6) which results in 或trunc count := trunc(3 / 1.6)导致

1 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. 您可能会认为,使用Google之类的工具很容易,但是请相信我并非如此。

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. C / C ++仅具有一个算术除法运算符- / -,但其行为取决于传递给它的操作数的类型。 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 . Delphi有两个算术除法运算div用于整数除法 ,和/用于浮点除法

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: 您的C ++代码正在执行浮点除法 ,然后将结果分配给DWORD ,这不是浮点类型,因此赋值会从小数点后截断:

1 / 1.699999 is 1.764706920415836 , which truncates to 1 . 1 / 1.6999991.764706920415836 ,将截断为1

In Delphi, the / operator returns an Extended , which is a floating-point type. 在Delphi中, /运算符返回Extended ,这是浮点类型。 Unlike C/C++, Delphi does not allow a floating-point type to be assigned directly to an integral type. 与C / C ++不同,Delphi不允许将浮点类型直接分配给整数类型。 You have to use Round() or Trunc() . 您必须使用Round()Trunc()

In this case, the Delphi equivalent of your C++ code is to use Trunc() : 在这种情况下,您的C ++代码的Delphi等效项是使用Trunc()

var
  count: DWORD;
begin
  count := Trunc(3 / 1.699999);
  Write(IntToStr(count));

The easiest is to use trunc(3 /1.699999). 最简单的方法是使用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 . 当然,为避免溢出, count应小于< maxInt div 1000000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM